Skip to main content

devflow_core/
state.rs

1//! DevFlow state machine.
2//!
3//! Drives the development workflow through a single linear chain of five stages:
4//! Define → Plan → Code → Validate → Ship. See [`crate::stage::Stage`].
5
6use serde::{Deserialize, Serialize};
7use std::fmt;
8use std::path::PathBuf;
9use std::str::FromStr;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use crate::mode::Mode;
13use crate::phase_id::PhaseId;
14use crate::stage::Stage;
15
16/// Full workflow state persisted to `.devflow/state.json`.
17///
18/// # Construction
19///
20/// Marked `#[non_exhaustive]`: downstream crates must build this through
21/// [`State::new`] and then assign the fields they care about, rather than by
22/// struct literal. Deserialization is unaffected — the `Deserialize` derive
23/// and every `#[serde(default)]` field keep working exactly as before, so
24/// state files written by older binaries still load.
25///
26/// This exists because `State` accumulates a field roughly every phase that
27/// adds a run-scoped concept (`worktree_path`, `monitor_pid`, `stop_until`,
28/// `yes_ship`, and — in phase 28 — `session_id` and `checkpoint_resumes`).
29/// Without `non_exhaustive`, each of those additions is a semver-breaking
30/// change for any consumer that used a struct literal, which would force a
31/// major bump for what is really an internal bookkeeping change. Paying that
32/// cost once here makes every future field additive.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34#[non_exhaustive]
35pub struct State {
36    /// Current workflow stage.
37    pub stage: Stage,
38    /// Phase number being worked on.
39    pub phase: PhaseId,
40    /// Which coding agent was launched.
41    pub agent: AgentKind,
42    /// How the pipeline is driven (auto vs. supervise).
43    pub mode: Mode,
44    /// Whether a gate has been written and is awaiting a human response.
45    #[serde(default)]
46    pub gate_pending: bool,
47    /// Consecutive Validate failures — drives the Auto-mode forced gate after
48    /// [`crate::mode::MAX_CONSECUTIVE_FAILURES`] failures. Persisted across
49    /// `devflow advance` invocations so the counter survives monitor restarts.
50    #[serde(default)]
51    pub consecutive_failures: u32,
52    /// Consecutive infrastructure-class faults (`ResourceKilled`,
53    /// `AgentUnavailable`) — distinct from [`Self::consecutive_failures`]
54    /// (D-08, 17-01). Gates at [`crate::mode::MAX_INFRA_FAILURES`]. Any
55    /// increment (wired in Plan 04) must use `saturating_add` so a
56    /// long-running stuck loop cannot overflow `u32`. A serde-absent value
57    /// (older persisted state) defaults to 0. Reset to 0 on every successful
58    /// stage transition, alongside `consecutive_failures` (CR-01, 17-06 gap
59    /// closure), so the ceiling bounds a stuck loop, not a phase's lifetime.
60    #[serde(default)]
61    pub infra_failures: u32,
62    /// How many times a preflight gate has been resolved and retried for
63    /// this phase (18f). Bounded by [`crate::mode::MAX_PREFLIGHT_RETRIES`].
64    /// Persisted rather than recursion-scoped because the documented wedge
65    /// spanned separate `devflow` invocations after a monitor death — an
66    /// in-process recursion-depth counter would reset to zero on every new
67    /// process and fail to bound the exact incident it exists to prevent.
68    /// Reset to 0 whenever preflight passes and whenever a human explicitly
69    /// approves (`GateAction::Advance`), both inside `run_preflight`. Unlike
70    /// [`Self::consecutive_failures`] and [`Self::infra_failures`], this
71    /// counter is NOT touched by `transition()`.
72    #[serde(default)]
73    pub preflight_retries: u32,
74    /// The commit count observed on the phase's feature branch at the most
75    /// recent Validate failure (999.66, D-03) — the forward-progress
76    /// baseline [`crate::mode::consecutive_failures_made_progress`] compares
77    /// against to decide whether a new failure begins a fresh streak or
78    /// continues the existing one.
79    ///
80    /// `None` means no prior failure has been recorded — either the first
81    /// failure of a phase, or the first failure observed after resuming
82    /// state written by a binary predating this field — and is deliberately
83    /// distinct from `Some(0)`, which means a failure WAS recorded and the
84    /// branch genuinely carried zero commits at that moment; a later failure
85    /// that again counts zero commits must accumulate against that `Some(0)`
86    /// baseline rather than being treated as a fresh streak.
87    ///
88    /// A serde-absent value (state written by a binary predating this field)
89    /// deserializes to `None`, which is exactly the "no prior record"
90    /// meaning above — the same backward-compat pattern as every other
91    /// `#[serde(default)]` field added since 17-01.
92    ///
93    /// Unlike [`Self::consecutive_failures`] and [`Self::infra_failures`],
94    /// this field is NOT touched by `transition()` — it is a baseline
95    /// observation rather than a counter, matching how
96    /// [`Self::preflight_retries`] and [`Self::checkpoint_resumes`] are
97    /// handled. It is replaced wholesale at each failure rather than
98    /// incremented, so it needs no `saturating_add` treatment, unlike every
99    /// other numeric field on this struct.
100    #[serde(default)]
101    pub last_validate_failure_commit_count: Option<u32>,
102    /// Every Validate failure recorded for this PHASE, accumulated without
103    /// regard to forward progress (999.78/WR-01, D-07) — the backstop bound
104    /// [`crate::mode::MAX_PHASE_VALIDATE_FAILURES`] compares against, and the
105    /// leading number in the Supervise gate message (WR-04).
106    ///
107    /// A serde-absent value (state written by a binary predating this field)
108    /// deserializes to 0, which is exactly its "no failures recorded for this
109    /// phase" meaning — the same backward-compat pattern as every other
110    /// `#[serde(default)]` field added since 17-01. Unlike
111    /// [`Self::last_validate_failure_commit_count`], zero is not ambiguous
112    /// here: an upgraded binary and a genuine first failure both start the
113    /// budget at its full width, and that widening is what IN-02's distinct
114    /// loop-back reason exists to announce.
115    ///
116    /// Why it exists next to [`Self::consecutive_failures`] rather than
117    /// replacing it: `consecutive_failures` is reset whenever
118    /// [`crate::mode::consecutive_failures_made_progress`] reports that new
119    /// commits landed, and the Code stage's fix command is a GSD command
120    /// which routinely commits `.planning/` artifacts even when no source
121    /// changed. A loop that commits something trivial every cycle therefore
122    /// resets the streak every cycle and never reaches
123    /// [`crate::mode::MAX_CONSECUTIVE_FAILURES`]. This total cannot be reset
124    /// by a commit count.
125    ///
126    /// **Lifetime — deliberately unlike every other counter on this struct.**
127    /// It is NOT touched by the stage transition (`transition_resets_*` has no
128    /// say over it), matching how [`Self::preflight_retries`] and
129    /// [`Self::checkpoint_resumes`] are handled, because it is a per-phase
130    /// total rather than a per-streak counter. It is also carried across a
131    /// forced restart: `commands::start()` reads any persisted state for the
132    /// same phase and copies this one field into the fresh `State`, because a
133    /// bound a `devflow start --force` resets does not bound the unattended
134    /// case D-07 exists for. Exactly two events reset it to zero:
135    ///
136    /// 1. **Phase completion** — `finish_workflow_with_gate_timeout` calls
137    ///    `workflow::clear_state`, deleting `.devflow/state-{NN}.json`, so the
138    ///    next start for that phase finds nothing to carry.
139    /// 2. **Operator approval at the ceiling gate** — the Validate gate
140    ///    handling zeroes it when a human advances or loops back AND
141    ///    [`crate::mode::phase_failure_ceiling_reached`] is true. Keyed on that
142    ///    predicate and never on "a gate fired": Supervise gates on every
143    ///    Validate, so a gate-keyed reset would clear the total at every
144    ///    failure and it would never accumulate in the one mode where an
145    ///    operator watches every occurrence.
146    ///
147    /// Any increment must use `saturating_add`, like [`Self::infra_failures`]
148    /// and [`Self::checkpoint_resumes`], so an exhausted budget can never wrap
149    /// back to zero and silently restore itself.
150    #[serde(default)]
151    pub phase_validate_failures: u32,
152    /// The content fingerprint of this phase's `{N}-VERIFICATION.md` as it
153    /// stood at the START of this run (999.79), read via
154    /// [`crate::agent_result::phase_verification_fingerprint`] once the
155    /// evidence root for the run is known.
156    ///
157    /// `None` means no artifact was observed at the start of this run — the
158    /// ordinary case for a phase being executed for the first time. It is
159    /// deliberately distinct from `Some(h)`: an artifact that EXISTS now where
160    /// the baseline recorded none was authored during this run, whereas an
161    /// artifact whose fingerprint still equals the baseline was inherited from
162    /// a previous run and its verdict must not be reused.
163    ///
164    /// **State written by a binary predating this field also deserializes to
165    /// `None`, and that is NOT the same reading** (WR-05, 35-REVIEW). This doc
166    /// comment used to claim it was. For a phase started under an older binary
167    /// and continued by this one, the previous run's committed
168    /// `{N}-VERIFICATION.md` is already on disk while the baseline reads
169    /// `None` — so the `(Some, None)` row would classify an inherited artifact
170    /// as authored-this-run and dispatch `--gaps-only` against zero matching
171    /// plans, gating unresolvably. That is verbatim the DOGFOOD-01-class stall
172    /// 999.79 exists to close, reproduced for every in-flight phase across the
173    /// upgrade.
174    ///
175    /// [`Self::verification_baseline_captured`] is the discriminator: only a
176    /// run that actually performed the observation sets it, so a `None` from an
177    /// old state file is distinguishable from a `None` that means "looked, and
178    /// there was nothing there".
179    ///
180    /// Why this exists at all: nothing deletes or dates `{N}-VERIFICATION.md`,
181    /// so a `devflow start --force` re-run checks out a branch still carrying
182    /// the previous run's committed copy. Without this baseline the first
183    /// Validate failure of that re-run reads the inherited artifact as a
184    /// verdict and dispatches a `--gaps-only` pass against zero matching plans,
185    /// which gates unresolvably — the same unattended-stall class as
186    /// DOGFOOD-01, reached from a different direction.
187    ///
188    /// **Lifetime.** Like [`Self::last_validate_failure_commit_count`], and
189    /// unlike [`Self::consecutive_failures`] and [`Self::infra_failures`], this
190    /// field is NOT touched by `transition()` — it is a run-scoped observation
191    /// rather than a counter, so it is replaced wholesale rather than
192    /// incremented and needs no `saturating_add` treatment. It is also NOT
193    /// carried across a forced restart the way
194    /// [`Self::phase_validate_failures`] is: a new run must re-observe the
195    /// artifact, because the whole point is to compare against what THIS run
196    /// started with.
197    #[serde(default)]
198    pub last_verification_fingerprint: Option<u64>,
199    /// Whether [`Self::last_verification_fingerprint`] was actually observed by
200    /// this run, as opposed to merely absent (WR-05, 35-REVIEW).
201    ///
202    /// `Option<u64>` cannot carry this on its own: `None` means both "the run
203    /// looked and found no artifact" and "this state file predates the field,
204    /// so nobody ever looked", and those two demand OPPOSITE dispatches. The
205    /// first is the ordinary first-verification case and `--gaps-only` is
206    /// right; the second may be sitting on an inherited artifact, where
207    /// `--gaps-only` matches zero plans and stalls.
208    ///
209    /// `false` is therefore the correct serde default in both directions: a
210    /// state file written before this field existed genuinely did not capture a
211    /// baseline, and the conservative reading of an artifact whose provenance
212    /// is unknown is "inherited" — a full execute is wasteful, an unresolvable
213    /// gate is not recoverable.
214    ///
215    /// Set exactly once per run, at the same site that captures the baseline,
216    /// after `state.worktree_path` holds its final value.
217    #[serde(default)]
218    pub verification_baseline_captured: bool,
219    /// The mtime of the same artifact [`Self::last_verification_fingerprint`]
220    /// hashes, in nanoseconds since the Unix epoch, as of the same observation.
221    ///
222    /// WR-06 (35-REVIEW): a content fingerprint cannot see an IDEMPOTENT
223    /// rewrite. A Validate agent that re-authors byte-identical content on a
224    /// later failing cycle produces the same hash as an artifact nobody
225    /// touched, so a hash-only rule reads its own agent's work as inherited and
226    /// dispatches a full execute — re-running every plan in the phase on every
227    /// subsequent cycle instead of the gaps-only pass Phase 33 built. That is
228    /// the "too strict" direction the freshness rule's own comment claims to
229    /// guard against and did not.
230    ///
231    /// Moves in lockstep with the fingerprint: written at the same capture
232    /// site, replaced at the same update site, and never read on its own — the
233    /// pair is the observation, and either one differing means the artifact was
234    /// written during this run.
235    ///
236    /// 35.2 D-05: mtime was considered as the provenance signal and REJECTED.
237    /// A branch checkout or worktree merge-back updates mtime exactly as a
238    /// real write does — it fails on the identical scenario
239    /// [`Self::verification_run_nonce`] exists to catch, which is why 999.89
240    /// survived 35-05's WR-06 fix. mtime is still what detects a byte-identical
241    /// rewrite INSIDE the Validate dispatch window whose bounds the nonce
242    /// establishes — provenance and freshness are different questions.
243    #[serde(default)]
244    pub last_verification_mtime_nanos: Option<u64>,
245    /// A run-owned marker stamped per Validate dispatch proving DevFlow itself
246    /// launched the agent whose output this state describes (35.2, 999.89 /
247    /// HARDEN-03, D-01).
248    ///
249    /// `None` means DevFlow never stamped a Validate dispatch for this state,
250    /// which is both the pre-35.2-state-file case and the never-dispatched
251    /// case. Both demand the conservative reading: the artifact's provenance is
252    /// unknown and `verification_authored_this_run` returns `false`.
253    ///
254    /// **Lifetime — replaced wholesale on every Validate dispatch, not
255    /// incremented across runs.** Unlike [`Self::consecutive_failures`] and
256    /// [`Self::phase_validate_failures`], this field is NOT touched by
257    /// `transition()`, and [`State::new`] resets it, so a `--force` restart
258    /// cannot inherit a previous run's stamp. The value is a monotonically
259    /// increasing counter; the predicate consults [`Option::is_some`], never
260    /// the magnitude, so saturation cannot degrade the signal.
261    ///
262    /// The write site is `launch_stage_inner` in `pipeline_launch.rs`, gated
263    /// on `Stage::Validate`, co-located with a fresh fingerprint/mtime
264    /// re-observation — the stamp and the baseline are one mechanism, and
265    /// splitting them silently restores the run-wide observation window.
266    ///
267    /// An actor who can write `.devflow/state-{N}.json` can set `stage` or
268    /// `consecutive_failures` directly; this field adds no attack surface
269    /// beyond what already exists (P-03).
270    #[serde(default)]
271    pub verification_run_nonce: Option<u64>,
272    /// When the phase started (Unix seconds).
273    pub started_at: String,
274    /// Path to the project root.
275    pub project_root: PathBuf,
276    /// Working directory for the agent when running in a git worktree.
277    ///
278    /// `None` means the agent runs in `project_root`. State and capture files
279    /// always live under the main `project_root`; only the agent's cwd changes.
280    #[serde(default)]
281    pub worktree_path: Option<PathBuf>,
282    /// PID of the detached monitor process that owns the agent for the
283    /// current stage, recorded by `launch_stage` at spawn time. `None` means
284    /// no monitor has been spawned for this state yet, OR the state was
285    /// written by a binary predating this field — in both cases the
286    /// liveness probe reports Unknown, never Stuck.
287    #[serde(default)]
288    pub monitor_pid: Option<u32>,
289    /// The Claude session id captured from the most recent captured stdout
290    /// envelope for this phase's current stage (D-04, 28-02), read via
291    /// [`crate::agent_result::session_id_from_capture`]. `None` means EITHER
292    /// "no session has been captured for this state yet" OR "the state was
293    /// written by a binary predating this field" — both cases behave
294    /// identically (no relaunch target to address). Recorded so a checkpoint
295    /// auto-decide relaunch (plan 28-03) can `--resume` the exact session
296    /// that hit the checkpoint rather than spawning a fresh one, which would
297    /// lose the original session's conversation context and permission mode.
298    #[serde(default)]
299    pub session_id: Option<String>,
300    /// How many times the current stage's agent has been relaunched via a
301    /// checkpoint auto-decide resume (D-04, 28-03). Bounds a stuck
302    /// checkpoint loop against `mode::MAX_CHECKPOINT_RESUMES` (added in plan
303    /// 28-03) the same way [`Self::infra_failures`] bounds an infra-fault
304    /// loop against `mode::MAX_INFRA_FAILURES`. Reset to 0 by every ordinary fresh stage
305    /// launch, so the ceiling bounds one stage's resume budget, not a
306    /// phase's lifetime (the same distinction `MAX_INFRA_FAILURES`' doc
307    /// comment draws for `infra_failures`). Any increment must use
308    /// `saturating_add` so a stuck loop cannot overflow `u32`. A
309    /// serde-absent value (state written by a binary predating this field)
310    /// defaults to 0.
311    #[serde(default)]
312    pub checkpoint_resumes: u32,
313    /// The stage `devflow start --until <stage>` requests as the last stage
314    /// to run before halting (20c). `None` means no stop point was
315    /// requested (the pipeline runs to Ship), OR the state was written by a
316    /// binary predating this field — both cases behave identically (no
317    /// interception in `transition()`).
318    #[serde(default)]
319    pub stop_until: Option<Stage>,
320    /// Set by `transition()` when `stop_until` names the stage just
321    /// completed — a terminal-but-not-failed halt short of Ship (20c).
322    /// `false` for a normal in-flight or completed-to-Ship phase, and for
323    /// any state written by a binary predating this field.
324    #[serde(default)]
325    pub stopped: bool,
326    /// Human-readable reason recorded alongside `stopped` (20c). `None`
327    /// when `stopped` is `false`, or when the state predates this field.
328    #[serde(default)]
329    pub stop_reason: Option<String>,
330    /// Pre-authorization for the Ship gate (D-04/D-05/D-06, 23-09),
331    /// set only from the `--yes-ship` CLI flag typed on `devflow start`.
332    ///
333    /// Persisted rather than passed through the call stack: the Ship gate
334    /// fires inside a detached monitor's `advance` process, minutes to
335    /// hours after the launching `devflow start` process has already
336    /// exited, so a CLI-scoped value would be gone by the time it matters —
337    /// only a value written to `state.json` at start time survives to be
338    /// read back by that later, separate process. `false` for any state
339    /// written by a binary predating this field.
340    #[serde(default)]
341    pub yes_ship: bool,
342    /// What this run's delivery canary established (D-13/D-15, 31-03),
343    /// recorded by the first stage launch that routes through the Claude
344    /// `stream-json` transport. `None` means EITHER "no canary has run for
345    /// this run yet" OR "the state was written by a binary predating this
346    /// field" — both cases behave identically: the canary runs.
347    ///
348    /// Persisted rather than held in memory for the same reason
349    /// [`Self::yes_ship`] is: each stage launch happens in a SEPARATE
350    /// `devflow` process (the monitor's own `advance` tail), so an
351    /// in-process flag would reset to "not yet run" at every stage
352    /// transition and re-spend a real throwaway agent invocation each time —
353    /// which is exactly the symptom 31-RESEARCH Pitfall 5 names for a canary
354    /// that landed in the per-stage `preflight` hook.
355    ///
356    /// A recorded `Absent`/`Unverified` keeps refusing on every later launch
357    /// in the run; it is not consumed by the first refusal.
358    #[serde(default)]
359    pub canary: Option<crate::canary::CanaryOutcome>,
360    /// D-11's opt-out: force the pre-31 single-document Claude launch
361    /// (positional prompt, `--output-format json`, the `sh` monitor) for this
362    /// run, off by default.
363    ///
364    /// `false` means EITHER "the operator did not ask for the legacy path" OR
365    /// "the state was written by a binary predating this field" — both cases
366    /// behave identically: the D-09/D-10 rollout decides the transport, which
367    /// is the pre-existing behaviour.
368    ///
369    /// Persisted rather than passed through the call stack for the reason
370    /// [`Self::yes_ship`] gives: each stage launch happens in a SEPARATE
371    /// `devflow` process (the detached monitor's own `advance` tail), so a
372    /// CLI-scoped value would be gone by the time the second stage launches
373    /// and the run would silently revert to the stream transport mid-flight.
374    ///
375    /// Only ever OR-ed, never cleared, once set — see
376    /// `pipeline_launch::apply_legacy_launch_opt_out`. Clearing it on a plain
377    /// `devflow resume` would be the same silent-drop class as `stop_until`'s
378    /// old unconditional clear (999.60). To turn it back off, edit
379    /// `.devflow/state-NN.json` or start a new run.
380    #[serde(default)]
381    pub legacy_claude_launch: bool,
382}
383
384/// Supported coding agents.
385#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
386#[serde(rename_all = "lowercase")]
387pub enum AgentKind {
388    /// Anthropic Claude Code CLI.
389    Claude,
390    /// OpenAI Codex CLI.
391    Codex,
392    /// OpenCode CLI.
393    OpenCode,
394    /// Pi coding-agent harness.
395    Pi,
396}
397
398impl fmt::Display for AgentKind {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        let name = match self {
401            AgentKind::Claude => "claude",
402            AgentKind::Codex => "codex",
403            AgentKind::OpenCode => "opencode",
404            AgentKind::Pi => "pi",
405        };
406        f.write_str(name)
407    }
408}
409
410impl FromStr for AgentKind {
411    type Err = AgentParseError;
412
413    fn from_str(value: &str) -> Result<Self, Self::Err> {
414        match value.to_ascii_lowercase().as_str() {
415            "claude" => Ok(AgentKind::Claude),
416            "codex" => Ok(AgentKind::Codex),
417            "opencode" | "open-code" => Ok(AgentKind::OpenCode),
418            "pi" => Ok(AgentKind::Pi),
419            other => Err(AgentParseError(other.to_string())),
420        }
421    }
422}
423
424/// Error returned when parsing an unsupported agent name.
425#[derive(Debug, Clone, thiserror::Error)]
426#[error("unsupported agent `{0}`; expected claude, codex, opencode, or pi")]
427pub struct AgentParseError(String);
428
429impl State {
430    /// Create a new state for starting a phase at the [`Stage::Define`] stage.
431    pub fn new(phase: PhaseId, agent: AgentKind, mode: Mode, project_root: PathBuf) -> Self {
432        State {
433            stage: Stage::Define,
434            phase,
435            agent,
436            mode,
437            gate_pending: false,
438            consecutive_failures: 0,
439            infra_failures: 0,
440            preflight_retries: 0,
441            last_validate_failure_commit_count: None,
442            phase_validate_failures: 0,
443            last_verification_fingerprint: None,
444            verification_baseline_captured: false,
445            last_verification_mtime_nanos: None,
446            verification_run_nonce: None,
447            started_at: timestamp_now(),
448            project_root,
449            worktree_path: None,
450            monitor_pid: None,
451            session_id: None,
452            checkpoint_resumes: 0,
453            stop_until: None,
454            stopped: false,
455            stop_reason: None,
456            yes_ship: false,
457            canary: None,
458            legacy_claude_launch: false,
459        }
460    }
461}
462
463fn timestamp_now() -> String {
464    match SystemTime::now().duration_since(UNIX_EPOCH) {
465        Ok(duration) => format!("{}", duration.as_secs()),
466        Err(_) => String::from("0"),
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473    use std::path::PathBuf;
474
475    #[test]
476    fn agent_name_and_display() {
477        use crate::agents::adapter_for;
478        assert_eq!(adapter_for(AgentKind::Claude).name(), "Claude Code");
479        assert_eq!(adapter_for(AgentKind::Codex).name(), "OpenAI Codex");
480        assert_eq!(adapter_for(AgentKind::OpenCode).name(), "OpenCode");
481
482        assert_eq!(AgentKind::Claude.to_string(), "claude");
483        assert_eq!(AgentKind::Codex.to_string(), "codex");
484        assert_eq!(AgentKind::OpenCode.to_string(), "opencode");
485    }
486
487    #[test]
488    fn agent_from_str_accepts_canonical_and_aliases() {
489        assert_eq!("claude".parse::<AgentKind>().unwrap(), AgentKind::Claude);
490        assert_eq!("CLAUDE".parse::<AgentKind>().unwrap(), AgentKind::Claude);
491        assert_eq!("codex".parse::<AgentKind>().unwrap(), AgentKind::Codex);
492        assert_eq!(
493            "opencode".parse::<AgentKind>().unwrap(),
494            AgentKind::OpenCode
495        );
496        assert_eq!(
497            "open-code".parse::<AgentKind>().unwrap(),
498            AgentKind::OpenCode
499        );
500    }
501
502    #[test]
503    fn agent_from_str_rejects_unknown() {
504        let err = "aider".parse::<AgentKind>().unwrap_err();
505        assert!(err.to_string().contains("aider"));
506    }
507
508    #[test]
509    fn new_state_starts_at_define() {
510        let state = State::new(
511            PhaseId::new(2),
512            AgentKind::Claude,
513            Mode::Auto,
514            PathBuf::from("/repo"),
515        );
516        assert_eq!(state.stage, Stage::Define);
517        assert_eq!(state.phase, PhaseId::new(2));
518        assert_eq!(state.agent, AgentKind::Claude);
519        assert_eq!(state.mode, Mode::Auto);
520        assert!(!state.gate_pending);
521        assert_eq!(state.consecutive_failures, 0);
522        assert_eq!(state.infra_failures, 0);
523        assert_eq!(state.preflight_retries, 0);
524        assert_eq!(state.phase_validate_failures, 0);
525        assert!(!state.started_at.is_empty());
526        assert_eq!(state.monitor_pid, None);
527        assert_eq!(state.stop_until, None);
528        assert!(!state.stopped);
529        assert_eq!(state.stop_reason, None);
530        assert!(!state.yes_ship);
531    }
532
533    #[test]
534    fn state_serde_round_trips() {
535        let state = State::new(
536            PhaseId::new(9),
537            AgentKind::Codex,
538            Mode::Supervise,
539            PathBuf::from("/repo"),
540        );
541        let json = serde_json::to_string(&state).unwrap();
542        let back: State = serde_json::from_str(&json).unwrap();
543        assert_eq!(back.phase, PhaseId::new(9));
544        assert_eq!(back.agent, AgentKind::Codex);
545        assert_eq!(back.stage, Stage::Define);
546        assert_eq!(back.mode, Mode::Supervise);
547    }
548
549    #[test]
550    fn consecutive_failures_persists_across_advance_calls() {
551        let mut state = State::new(
552            PhaseId::new(1),
553            AgentKind::Claude,
554            Mode::Auto,
555            PathBuf::from("/repo"),
556        );
557        state.consecutive_failures = 3;
558        let json = serde_json::to_string(&state).unwrap();
559        assert!(
560            json.contains("consecutive_failures"),
561            "consecutive_failures must appear in persisted JSON"
562        );
563        let loaded: State = serde_json::from_str(&json).unwrap();
564        assert_eq!(
565            loaded.consecutive_failures, 3,
566            "consecutive_failures must round-trip through serde"
567        );
568    }
569
570    /// D-08 (17-01): a distinct infra-failure counter round-trips through
571    /// serde and its own key appears in the persisted JSON.
572    #[test]
573    fn infra_failures_round_trips_through_serde() {
574        let mut state = State::new(
575            PhaseId::new(1),
576            AgentKind::Claude,
577            Mode::Auto,
578            PathBuf::from("/repo"),
579        );
580        state.infra_failures = 4;
581        let json = serde_json::to_string(&state).unwrap();
582        assert!(
583            json.contains("infra_failures"),
584            "infra_failures must appear in persisted JSON"
585        );
586        let loaded: State = serde_json::from_str(&json).unwrap();
587        assert_eq!(
588            loaded.infra_failures, 4,
589            "infra_failures must round-trip through serde"
590        );
591    }
592
593    /// A serde-absent `infra_failures` (older persisted state.json without
594    /// the field) must default to 0, not fail to deserialize.
595    #[test]
596    fn infra_failures_absent_from_json_defaults_to_zero() {
597        let json = r#"{
598            "stage": "code",
599            "phase": 1,
600            "agent": "claude",
601            "mode": "auto",
602            "started_at": "0",
603            "project_root": "/repo"
604        }"#;
605        let loaded: State = serde_json::from_str(json).unwrap();
606        assert_eq!(loaded.infra_failures, 0);
607    }
608
609    /// `last_validate_failure_commit_count` round-trips through serde as an
610    /// exact `Option<u32>` (999.66, D-03) — its own key appears in the
611    /// persisted JSON before the value round-trip is asserted, so a field
612    /// accidentally attributed `skip_serializing_if` (which would still pass
613    /// a naive in-memory round-trip while never persisting anything) is
614    /// caught.
615    #[test]
616    fn last_validate_failure_commit_count_round_trips_through_serde() {
617        let mut state = State::new(
618            PhaseId::new(1),
619            AgentKind::Claude,
620            Mode::Auto,
621            PathBuf::from("/repo"),
622        );
623        state.last_validate_failure_commit_count = Some(3);
624        let json = serde_json::to_string(&state).unwrap();
625        assert!(
626            json.contains("last_validate_failure_commit_count"),
627            "last_validate_failure_commit_count must appear in persisted JSON"
628        );
629        let loaded: State = serde_json::from_str(&json).unwrap();
630        assert_eq!(
631            loaded.last_validate_failure_commit_count,
632            Some(3),
633            "last_validate_failure_commit_count must round-trip through serde"
634        );
635    }
636
637    /// A serde-absent `last_validate_failure_commit_count` (state written by
638    /// a binary predating this field) must deserialize to `None` — the
639    /// "no prior failure recorded" meaning — not to `Some(0)`, which would
640    /// misrepresent a never-observed baseline as an observed zero.
641    #[test]
642    fn last_validate_failure_commit_count_absent_from_json_defaults_to_none() {
643        let json = r#"{
644            "stage": "code",
645            "phase": 1,
646            "agent": "claude",
647            "mode": "auto",
648            "started_at": "0",
649            "project_root": "/repo"
650        }"#;
651        let loaded: State = serde_json::from_str(json).unwrap();
652        assert_eq!(loaded.last_validate_failure_commit_count, None);
653    }
654
655    /// 999.78/D-07: `phase_validate_failures` round-trips through serde. The
656    /// key-presence assertion comes BEFORE the value round-trip deliberately —
657    /// a field that never actually persists still passes a naive in-memory
658    /// round trip, and a bound that lives only in memory does not bound a
659    /// phase whose whole failure mode spans separate `devflow` processes.
660    #[test]
661    fn phase_validate_failures_round_trips_through_serde() {
662        let mut state = State::new(
663            PhaseId::new(1),
664            AgentKind::Claude,
665            Mode::Auto,
666            PathBuf::from("/repo"),
667        );
668        state.phase_validate_failures = 7;
669        let json = serde_json::to_string(&state).unwrap();
670        assert!(
671            json.contains("phase_validate_failures"),
672            "phase_validate_failures must appear in persisted JSON"
673        );
674        let loaded: State = serde_json::from_str(&json).unwrap();
675        assert_eq!(
676            loaded.phase_validate_failures, 7,
677            "phase_validate_failures must round-trip through serde"
678        );
679    }
680
681    /// A serde-absent `phase_validate_failures` (state written by a binary
682    /// predating this field) deserializes to 0 — "no failures recorded for
683    /// this phase" — rather than failing the load outright, which would make
684    /// an upgrade mid-phase unrecoverable.
685    #[test]
686    fn phase_validate_failures_absent_from_json_defaults_to_zero() {
687        let json = r#"{
688            "stage": "code",
689            "phase": 1,
690            "agent": "claude",
691            "mode": "auto",
692            "started_at": "0",
693            "project_root": "/repo"
694        }"#;
695        let loaded: State = serde_json::from_str(json).unwrap();
696        assert_eq!(loaded.phase_validate_failures, 0);
697    }
698
699    /// 999.79 (35-05): `last_verification_fingerprint` round-trips through
700    /// serde. The key-presence assertion comes BEFORE the value round-trip for
701    /// the same reason the two fields above give — this baseline is written by
702    /// `devflow start` and compared by a later `devflow advance`, which is a
703    /// different process, so a field that never reaches disk would leave every
704    /// comparison reading `None` and defeat the whole rule.
705    #[test]
706    fn last_verification_fingerprint_round_trips_through_serde() {
707        let mut state = State::new(
708            PhaseId::new(1),
709            AgentKind::Claude,
710            Mode::Auto,
711            PathBuf::from("/repo"),
712        );
713        state.last_verification_fingerprint = Some(0x0123_4567_89ab_cdef);
714        let json = serde_json::to_string(&state).unwrap();
715        assert!(
716            json.contains("last_verification_fingerprint"),
717            "last_verification_fingerprint must appear in persisted JSON"
718        );
719        let loaded: State = serde_json::from_str(&json).unwrap();
720        assert_eq!(
721            loaded.last_verification_fingerprint,
722            Some(0x0123_4567_89ab_cdef),
723            "last_verification_fingerprint must round-trip through serde"
724        );
725    }
726
727    /// A serde-absent `last_verification_fingerprint` (state written by a
728    /// binary predating this field) deserializes to `None` — "no artifact was
729    /// observed at the start of this run" — rather than failing the load, which
730    /// would make an upgrade mid-phase unrecoverable.
731    #[test]
732    fn last_verification_fingerprint_absent_from_json_defaults_to_none() {
733        let json = r#"{
734            "stage": "code",
735            "phase": 1,
736            "agent": "claude",
737            "mode": "auto",
738            "started_at": "0",
739            "project_root": "/repo"
740        }"#;
741        let loaded: State = serde_json::from_str(json).unwrap();
742        assert_eq!(loaded.last_verification_fingerprint, None);
743        // WR-05 (35-REVIEW): the SAME absent JSON must also report that nobody
744        // captured a baseline. `None` alone cannot carry that — it means both
745        // "looked, found nothing" and "never looked" — and the two demand
746        // opposite dispatches downstream.
747        assert!(
748            !loaded.verification_baseline_captured,
749            "state predating the baseline field never captured one, and must not claim to"
750        );
751    }
752
753    /// The other half of the pair above: a state file written by THIS binary
754    /// carries the flag, so the two cases really are distinguishable after a
755    /// round trip. Without this, `verification_baseline_captured` could be
756    /// hardcoded `false` and the absent-JSON assertion above would still pass.
757    #[test]
758    fn verification_baseline_captured_round_trips_through_serde() {
759        let mut state = State::new(
760            PhaseId::new(1),
761            AgentKind::Claude,
762            Mode::Auto,
763            PathBuf::from("/repo"),
764        );
765        state.verification_baseline_captured = true;
766        let json = serde_json::to_string(&state).unwrap();
767        assert!(
768            json.contains("verification_baseline_captured"),
769            "verification_baseline_captured must appear in persisted JSON"
770        );
771        let loaded: State = serde_json::from_str(&json).unwrap();
772        assert!(
773            loaded.verification_baseline_captured,
774            "a captured baseline must survive the save/load the real pipeline performs"
775        );
776    }
777
778    /// 35.2 D-01: verification_run_nonce must survive the save/load cycle
779    /// `handle_validate_outcome` → `select_loop_back_fix` performs.
780    #[test]
781    fn verification_run_nonce_round_trips_through_serde() {
782        let mut state = State::new(
783            PhaseId::new(1),
784            AgentKind::Claude,
785            Mode::Auto,
786            PathBuf::from("/repo"),
787        );
788        state.verification_run_nonce = Some(42);
789        let json = serde_json::to_string(&state).unwrap();
790        assert!(
791            json.contains("verification_run_nonce"),
792            "verification_run_nonce must appear in persisted JSON"
793        );
794        let loaded: State = serde_json::from_str(&json).unwrap();
795        assert_eq!(
796            loaded.verification_run_nonce,
797            Some(42),
798            "verification_run_nonce must round-trip through serde"
799        );
800    }
801
802    /// 35.2 D-01: a serde-absent verification_run_nonce (state written by
803    /// a pre-35.2 binary) deserializes to None — the conservative direction.
804    #[test]
805    fn verification_run_nonce_absent_from_json_defaults_to_none() {
806        let json = r#"{
807            "stage": "code",
808            "phase": 1,
809            "agent": "claude",
810            "mode": "auto",
811            "started_at": "0",
812            "project_root": "/repo"
813        }"#;
814        let loaded: State = serde_json::from_str(json).unwrap();
815        assert_eq!(
816            loaded.verification_run_nonce, None,
817            "pre-35.2 state must default to None — the conservative provenance reading"
818        );
819    }
820
821    /// D-18f: `preflight_retries` round-trips through serde (its own key
822    /// appears in the persisted JSON) — the wedge this counter bounds spans
823    /// separate `devflow` invocations, so it must survive a save/load
824    /// cycle, not just live in memory — and a serde-absent value (state
825    /// written by a pre-18f binary) deserializes to 0, not a hard error.
826    #[test]
827    fn preflight_retries_round_trips_through_serde() {
828        let mut state = State::new(
829            PhaseId::new(1),
830            AgentKind::Claude,
831            Mode::Auto,
832            PathBuf::from("/repo"),
833        );
834        state.preflight_retries = 2;
835        let json = serde_json::to_string(&state).unwrap();
836        assert!(
837            json.contains("preflight_retries"),
838            "preflight_retries must appear in persisted JSON"
839        );
840        let loaded: State = serde_json::from_str(&json).unwrap();
841        assert_eq!(
842            loaded.preflight_retries, 2,
843            "preflight_retries must round-trip through serde"
844        );
845
846        let absent_json = r#"{
847            "stage": "code",
848            "phase": 1,
849            "agent": "claude",
850            "mode": "auto",
851            "started_at": "0",
852            "project_root": "/repo"
853        }"#;
854        let loaded_absent: State = serde_json::from_str(absent_json).unwrap();
855        assert_eq!(loaded_absent.preflight_retries, 0);
856    }
857
858    /// `monitor_pid` round-trips through serde as an exact `u32` (18b).
859    #[test]
860    fn monitor_pid_round_trips_through_serde() {
861        let mut state = State::new(
862            PhaseId::new(1),
863            AgentKind::Claude,
864            Mode::Auto,
865            PathBuf::from("/repo"),
866        );
867        state.monitor_pid = Some(4242);
868        let json = serde_json::to_string(&state).unwrap();
869        assert!(
870            json.contains("monitor_pid"),
871            "monitor_pid must appear in persisted JSON"
872        );
873        let loaded: State = serde_json::from_str(&json).unwrap();
874        assert_eq!(
875            loaded.monitor_pid,
876            Some(4242),
877            "monitor_pid must round-trip through serde"
878        );
879    }
880
881    /// A serde-absent `monitor_pid` (state written by a pre-18b binary) must
882    /// deserialize to `None`, not `Some(0)` — a `Some(0)` default would let a
883    /// pre-18b state file render as a monitor at pid 0.
884    #[test]
885    fn monitor_pid_absent_from_json_defaults_to_none() {
886        let json = r#"{
887            "stage": "code",
888            "phase": 1,
889            "agent": "claude",
890            "mode": "auto",
891            "started_at": "0",
892            "project_root": "/repo"
893        }"#;
894        let loaded: State = serde_json::from_str(json).unwrap();
895        assert_eq!(loaded.monitor_pid, None);
896    }
897
898    /// `session_id` round-trips through serde as an exact `Option<String>`
899    /// (D-04, 28-02) — mirrors the `monitor_pid` pair above.
900    #[test]
901    fn session_id_round_trips_through_serde() {
902        let mut state = State::new(
903            PhaseId::new(1),
904            AgentKind::Claude,
905            Mode::Auto,
906            PathBuf::from("/repo"),
907        );
908        state.session_id = Some("cf29bfec-69e8-45df-a4f3-3da08ab6f66e".to_string());
909        let json = serde_json::to_string(&state).unwrap();
910        assert!(
911            json.contains("session_id"),
912            "session_id must appear in persisted JSON"
913        );
914        let loaded: State = serde_json::from_str(&json).unwrap();
915        assert_eq!(
916            loaded.session_id.as_deref(),
917            Some("cf29bfec-69e8-45df-a4f3-3da08ab6f66e"),
918            "session_id must round-trip through serde"
919        );
920    }
921
922    /// A serde-absent `session_id` (state written by a pre-28-02 binary) must
923    /// deserialize to `None`, not fail to deserialize.
924    #[test]
925    fn session_id_absent_from_json_defaults_to_none() {
926        let json = r#"{
927            "stage": "code",
928            "phase": 1,
929            "agent": "claude",
930            "mode": "auto",
931            "started_at": "0",
932            "project_root": "/repo"
933        }"#;
934        let loaded: State = serde_json::from_str(json).unwrap();
935        assert_eq!(loaded.session_id, None);
936    }
937
938    /// `checkpoint_resumes` round-trips through serde as an exact `u32`
939    /// (D-04, 28-02).
940    #[test]
941    fn checkpoint_resumes_round_trips_through_serde() {
942        let mut state = State::new(
943            PhaseId::new(1),
944            AgentKind::Claude,
945            Mode::Auto,
946            PathBuf::from("/repo"),
947        );
948        state.checkpoint_resumes = 2;
949        let json = serde_json::to_string(&state).unwrap();
950        assert!(
951            json.contains("checkpoint_resumes"),
952            "checkpoint_resumes must appear in persisted JSON"
953        );
954        let loaded: State = serde_json::from_str(&json).unwrap();
955        assert_eq!(
956            loaded.checkpoint_resumes, 2,
957            "checkpoint_resumes must round-trip through serde"
958        );
959    }
960
961    /// A serde-absent `checkpoint_resumes` (state written by a pre-28-02
962    /// binary) must deserialize to `0`, not fail to deserialize.
963    #[test]
964    fn checkpoint_resumes_absent_from_json_defaults_to_zero() {
965        let json = r#"{
966            "stage": "code",
967            "phase": 1,
968            "agent": "claude",
969            "mode": "auto",
970            "started_at": "0",
971            "project_root": "/repo"
972        }"#;
973        let loaded: State = serde_json::from_str(json).unwrap();
974        assert_eq!(loaded.checkpoint_resumes, 0);
975    }
976
977    /// 23-09 Task 1: `yes_ship` round-trips through serde as an exact `bool`
978    /// — its own key appears in the persisted JSON, and a fresh deserialize
979    /// recovers the value set, mirroring the `monitor_pid` pair above.
980    #[test]
981    fn yes_ship_round_trips_through_serde() {
982        let mut state = State::new(
983            PhaseId::new(1),
984            AgentKind::Claude,
985            Mode::Auto,
986            PathBuf::from("/repo"),
987        );
988        state.yes_ship = true;
989        let json = serde_json::to_string(&state).unwrap();
990        assert!(
991            json.contains("yes_ship"),
992            "yes_ship must appear in persisted JSON"
993        );
994        let loaded: State = serde_json::from_str(&json).unwrap();
995        assert!(loaded.yes_ship, "yes_ship must round-trip through serde");
996    }
997
998    /// A serde-absent `yes_ship` (state written by a pre-23-09 binary) must
999    /// deserialize to `false`, not fail to deserialize — the same
1000    /// backward-compat pattern as every other `#[serde(default)]` field
1001    /// added since 17-01.
1002    #[test]
1003    fn yes_ship_absent_from_json_defaults_to_false() {
1004        let json = r#"{
1005            "stage": "code",
1006            "phase": 1,
1007            "agent": "claude",
1008            "mode": "auto",
1009            "started_at": "0",
1010            "project_root": "/repo"
1011        }"#;
1012        let loaded: State = serde_json::from_str(json).unwrap();
1013        assert!(!loaded.yes_ship);
1014    }
1015
1016    /// 20c: `stop_until`/`stopped`/`stop_reason` all round-trip through
1017    /// serde — each field's own key appears in the persisted JSON, and a
1018    /// fresh deserialize recovers the exact values set.
1019    #[test]
1020    fn stop_fields_round_trip_through_serde() {
1021        let mut state = State::new(
1022            PhaseId::new(1),
1023            AgentKind::Claude,
1024            Mode::Auto,
1025            PathBuf::from("/repo"),
1026        );
1027        state.stop_until = Some(Stage::Plan);
1028        state.stopped = true;
1029        state.stop_reason = Some("stopped after plan completed (--until plan)".to_string());
1030        let json = serde_json::to_string(&state).unwrap();
1031        assert!(
1032            json.contains("stop_until") && json.contains("stopped") && json.contains("stop_reason"),
1033            "all three stop fields must appear in persisted JSON: {json}"
1034        );
1035        let loaded: State = serde_json::from_str(&json).unwrap();
1036        assert_eq!(
1037            loaded.stop_until,
1038            Some(Stage::Plan),
1039            "stop_until must round-trip through serde"
1040        );
1041        assert!(loaded.stopped, "stopped must round-trip through serde");
1042        assert_eq!(
1043            loaded.stop_reason.as_deref(),
1044            Some("stopped after plan completed (--until plan)"),
1045            "stop_reason must round-trip through serde"
1046        );
1047    }
1048
1049    /// A serde-absent `stop_until`/`stopped`/`stop_reason` (state written by
1050    /// a pre-20c binary) must default to `None`/`false`/`None`, not fail to
1051    /// deserialize — the same backward-compat pattern as every other
1052    /// `#[serde(default)]` field added since 17-01.
1053    #[test]
1054    fn stop_fields_absent_from_json_default() {
1055        let json = r#"{
1056            "stage": "code",
1057            "phase": 1,
1058            "agent": "claude",
1059            "mode": "auto",
1060            "started_at": "0",
1061            "project_root": "/repo"
1062        }"#;
1063        let loaded: State = serde_json::from_str(json).unwrap();
1064        assert_eq!(loaded.stop_until, None);
1065        assert!(!loaded.stopped);
1066        assert_eq!(loaded.stop_reason, None);
1067    }
1068}