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}
395
396impl fmt::Display for AgentKind {
397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398        let name = match self {
399            AgentKind::Claude => "claude",
400            AgentKind::Codex => "codex",
401            AgentKind::OpenCode => "opencode",
402        };
403        f.write_str(name)
404    }
405}
406
407impl FromStr for AgentKind {
408    type Err = AgentParseError;
409
410    fn from_str(value: &str) -> Result<Self, Self::Err> {
411        match value.to_ascii_lowercase().as_str() {
412            "claude" => Ok(AgentKind::Claude),
413            "codex" => Ok(AgentKind::Codex),
414            "opencode" | "open-code" => Ok(AgentKind::OpenCode),
415            other => Err(AgentParseError(other.to_string())),
416        }
417    }
418}
419
420/// Error returned when parsing an unsupported agent name.
421#[derive(Debug, Clone, thiserror::Error)]
422#[error("unsupported agent `{0}`; expected claude, codex, or opencode")]
423pub struct AgentParseError(String);
424
425impl State {
426    /// Create a new state for starting a phase at the [`Stage::Define`] stage.
427    pub fn new(phase: PhaseId, agent: AgentKind, mode: Mode, project_root: PathBuf) -> Self {
428        State {
429            stage: Stage::Define,
430            phase,
431            agent,
432            mode,
433            gate_pending: false,
434            consecutive_failures: 0,
435            infra_failures: 0,
436            preflight_retries: 0,
437            last_validate_failure_commit_count: None,
438            phase_validate_failures: 0,
439            last_verification_fingerprint: None,
440            verification_baseline_captured: false,
441            last_verification_mtime_nanos: None,
442            verification_run_nonce: None,
443            started_at: timestamp_now(),
444            project_root,
445            worktree_path: None,
446            monitor_pid: None,
447            session_id: None,
448            checkpoint_resumes: 0,
449            stop_until: None,
450            stopped: false,
451            stop_reason: None,
452            yes_ship: false,
453            canary: None,
454            legacy_claude_launch: false,
455        }
456    }
457}
458
459fn timestamp_now() -> String {
460    match SystemTime::now().duration_since(UNIX_EPOCH) {
461        Ok(duration) => format!("{}", duration.as_secs()),
462        Err(_) => String::from("0"),
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use std::path::PathBuf;
470
471    #[test]
472    fn agent_name_and_display() {
473        use crate::agents::adapter_for;
474        assert_eq!(adapter_for(AgentKind::Claude).name(), "Claude Code");
475        assert_eq!(adapter_for(AgentKind::Codex).name(), "OpenAI Codex");
476        assert_eq!(adapter_for(AgentKind::OpenCode).name(), "OpenCode");
477
478        assert_eq!(AgentKind::Claude.to_string(), "claude");
479        assert_eq!(AgentKind::Codex.to_string(), "codex");
480        assert_eq!(AgentKind::OpenCode.to_string(), "opencode");
481    }
482
483    #[test]
484    fn agent_from_str_accepts_canonical_and_aliases() {
485        assert_eq!("claude".parse::<AgentKind>().unwrap(), AgentKind::Claude);
486        assert_eq!("CLAUDE".parse::<AgentKind>().unwrap(), AgentKind::Claude);
487        assert_eq!("codex".parse::<AgentKind>().unwrap(), AgentKind::Codex);
488        assert_eq!(
489            "opencode".parse::<AgentKind>().unwrap(),
490            AgentKind::OpenCode
491        );
492        assert_eq!(
493            "open-code".parse::<AgentKind>().unwrap(),
494            AgentKind::OpenCode
495        );
496    }
497
498    #[test]
499    fn agent_from_str_rejects_unknown() {
500        let err = "aider".parse::<AgentKind>().unwrap_err();
501        assert!(err.to_string().contains("aider"));
502    }
503
504    #[test]
505    fn new_state_starts_at_define() {
506        let state = State::new(
507            PhaseId::new(2),
508            AgentKind::Claude,
509            Mode::Auto,
510            PathBuf::from("/repo"),
511        );
512        assert_eq!(state.stage, Stage::Define);
513        assert_eq!(state.phase, PhaseId::new(2));
514        assert_eq!(state.agent, AgentKind::Claude);
515        assert_eq!(state.mode, Mode::Auto);
516        assert!(!state.gate_pending);
517        assert_eq!(state.consecutive_failures, 0);
518        assert_eq!(state.infra_failures, 0);
519        assert_eq!(state.preflight_retries, 0);
520        assert_eq!(state.phase_validate_failures, 0);
521        assert!(!state.started_at.is_empty());
522        assert_eq!(state.monitor_pid, None);
523        assert_eq!(state.stop_until, None);
524        assert!(!state.stopped);
525        assert_eq!(state.stop_reason, None);
526        assert!(!state.yes_ship);
527    }
528
529    #[test]
530    fn state_serde_round_trips() {
531        let state = State::new(
532            PhaseId::new(9),
533            AgentKind::Codex,
534            Mode::Supervise,
535            PathBuf::from("/repo"),
536        );
537        let json = serde_json::to_string(&state).unwrap();
538        let back: State = serde_json::from_str(&json).unwrap();
539        assert_eq!(back.phase, PhaseId::new(9));
540        assert_eq!(back.agent, AgentKind::Codex);
541        assert_eq!(back.stage, Stage::Define);
542        assert_eq!(back.mode, Mode::Supervise);
543    }
544
545    #[test]
546    fn consecutive_failures_persists_across_advance_calls() {
547        let mut state = State::new(
548            PhaseId::new(1),
549            AgentKind::Claude,
550            Mode::Auto,
551            PathBuf::from("/repo"),
552        );
553        state.consecutive_failures = 3;
554        let json = serde_json::to_string(&state).unwrap();
555        assert!(
556            json.contains("consecutive_failures"),
557            "consecutive_failures must appear in persisted JSON"
558        );
559        let loaded: State = serde_json::from_str(&json).unwrap();
560        assert_eq!(
561            loaded.consecutive_failures, 3,
562            "consecutive_failures must round-trip through serde"
563        );
564    }
565
566    /// D-08 (17-01): a distinct infra-failure counter round-trips through
567    /// serde and its own key appears in the persisted JSON.
568    #[test]
569    fn infra_failures_round_trips_through_serde() {
570        let mut state = State::new(
571            PhaseId::new(1),
572            AgentKind::Claude,
573            Mode::Auto,
574            PathBuf::from("/repo"),
575        );
576        state.infra_failures = 4;
577        let json = serde_json::to_string(&state).unwrap();
578        assert!(
579            json.contains("infra_failures"),
580            "infra_failures must appear in persisted JSON"
581        );
582        let loaded: State = serde_json::from_str(&json).unwrap();
583        assert_eq!(
584            loaded.infra_failures, 4,
585            "infra_failures must round-trip through serde"
586        );
587    }
588
589    /// A serde-absent `infra_failures` (older persisted state.json without
590    /// the field) must default to 0, not fail to deserialize.
591    #[test]
592    fn infra_failures_absent_from_json_defaults_to_zero() {
593        let json = r#"{
594            "stage": "code",
595            "phase": 1,
596            "agent": "claude",
597            "mode": "auto",
598            "started_at": "0",
599            "project_root": "/repo"
600        }"#;
601        let loaded: State = serde_json::from_str(json).unwrap();
602        assert_eq!(loaded.infra_failures, 0);
603    }
604
605    /// `last_validate_failure_commit_count` round-trips through serde as an
606    /// exact `Option<u32>` (999.66, D-03) — its own key appears in the
607    /// persisted JSON before the value round-trip is asserted, so a field
608    /// accidentally attributed `skip_serializing_if` (which would still pass
609    /// a naive in-memory round-trip while never persisting anything) is
610    /// caught.
611    #[test]
612    fn last_validate_failure_commit_count_round_trips_through_serde() {
613        let mut state = State::new(
614            PhaseId::new(1),
615            AgentKind::Claude,
616            Mode::Auto,
617            PathBuf::from("/repo"),
618        );
619        state.last_validate_failure_commit_count = Some(3);
620        let json = serde_json::to_string(&state).unwrap();
621        assert!(
622            json.contains("last_validate_failure_commit_count"),
623            "last_validate_failure_commit_count must appear in persisted JSON"
624        );
625        let loaded: State = serde_json::from_str(&json).unwrap();
626        assert_eq!(
627            loaded.last_validate_failure_commit_count,
628            Some(3),
629            "last_validate_failure_commit_count must round-trip through serde"
630        );
631    }
632
633    /// A serde-absent `last_validate_failure_commit_count` (state written by
634    /// a binary predating this field) must deserialize to `None` — the
635    /// "no prior failure recorded" meaning — not to `Some(0)`, which would
636    /// misrepresent a never-observed baseline as an observed zero.
637    #[test]
638    fn last_validate_failure_commit_count_absent_from_json_defaults_to_none() {
639        let json = r#"{
640            "stage": "code",
641            "phase": 1,
642            "agent": "claude",
643            "mode": "auto",
644            "started_at": "0",
645            "project_root": "/repo"
646        }"#;
647        let loaded: State = serde_json::from_str(json).unwrap();
648        assert_eq!(loaded.last_validate_failure_commit_count, None);
649    }
650
651    /// 999.78/D-07: `phase_validate_failures` round-trips through serde. The
652    /// key-presence assertion comes BEFORE the value round-trip deliberately —
653    /// a field that never actually persists still passes a naive in-memory
654    /// round trip, and a bound that lives only in memory does not bound a
655    /// phase whose whole failure mode spans separate `devflow` processes.
656    #[test]
657    fn phase_validate_failures_round_trips_through_serde() {
658        let mut state = State::new(
659            PhaseId::new(1),
660            AgentKind::Claude,
661            Mode::Auto,
662            PathBuf::from("/repo"),
663        );
664        state.phase_validate_failures = 7;
665        let json = serde_json::to_string(&state).unwrap();
666        assert!(
667            json.contains("phase_validate_failures"),
668            "phase_validate_failures must appear in persisted JSON"
669        );
670        let loaded: State = serde_json::from_str(&json).unwrap();
671        assert_eq!(
672            loaded.phase_validate_failures, 7,
673            "phase_validate_failures must round-trip through serde"
674        );
675    }
676
677    /// A serde-absent `phase_validate_failures` (state written by a binary
678    /// predating this field) deserializes to 0 — "no failures recorded for
679    /// this phase" — rather than failing the load outright, which would make
680    /// an upgrade mid-phase unrecoverable.
681    #[test]
682    fn phase_validate_failures_absent_from_json_defaults_to_zero() {
683        let json = r#"{
684            "stage": "code",
685            "phase": 1,
686            "agent": "claude",
687            "mode": "auto",
688            "started_at": "0",
689            "project_root": "/repo"
690        }"#;
691        let loaded: State = serde_json::from_str(json).unwrap();
692        assert_eq!(loaded.phase_validate_failures, 0);
693    }
694
695    /// 999.79 (35-05): `last_verification_fingerprint` round-trips through
696    /// serde. The key-presence assertion comes BEFORE the value round-trip for
697    /// the same reason the two fields above give — this baseline is written by
698    /// `devflow start` and compared by a later `devflow advance`, which is a
699    /// different process, so a field that never reaches disk would leave every
700    /// comparison reading `None` and defeat the whole rule.
701    #[test]
702    fn last_verification_fingerprint_round_trips_through_serde() {
703        let mut state = State::new(
704            PhaseId::new(1),
705            AgentKind::Claude,
706            Mode::Auto,
707            PathBuf::from("/repo"),
708        );
709        state.last_verification_fingerprint = Some(0x0123_4567_89ab_cdef);
710        let json = serde_json::to_string(&state).unwrap();
711        assert!(
712            json.contains("last_verification_fingerprint"),
713            "last_verification_fingerprint must appear in persisted JSON"
714        );
715        let loaded: State = serde_json::from_str(&json).unwrap();
716        assert_eq!(
717            loaded.last_verification_fingerprint,
718            Some(0x0123_4567_89ab_cdef),
719            "last_verification_fingerprint must round-trip through serde"
720        );
721    }
722
723    /// A serde-absent `last_verification_fingerprint` (state written by a
724    /// binary predating this field) deserializes to `None` — "no artifact was
725    /// observed at the start of this run" — rather than failing the load, which
726    /// would make an upgrade mid-phase unrecoverable.
727    #[test]
728    fn last_verification_fingerprint_absent_from_json_defaults_to_none() {
729        let json = r#"{
730            "stage": "code",
731            "phase": 1,
732            "agent": "claude",
733            "mode": "auto",
734            "started_at": "0",
735            "project_root": "/repo"
736        }"#;
737        let loaded: State = serde_json::from_str(json).unwrap();
738        assert_eq!(loaded.last_verification_fingerprint, None);
739        // WR-05 (35-REVIEW): the SAME absent JSON must also report that nobody
740        // captured a baseline. `None` alone cannot carry that — it means both
741        // "looked, found nothing" and "never looked" — and the two demand
742        // opposite dispatches downstream.
743        assert!(
744            !loaded.verification_baseline_captured,
745            "state predating the baseline field never captured one, and must not claim to"
746        );
747    }
748
749    /// The other half of the pair above: a state file written by THIS binary
750    /// carries the flag, so the two cases really are distinguishable after a
751    /// round trip. Without this, `verification_baseline_captured` could be
752    /// hardcoded `false` and the absent-JSON assertion above would still pass.
753    #[test]
754    fn verification_baseline_captured_round_trips_through_serde() {
755        let mut state = State::new(
756            PhaseId::new(1),
757            AgentKind::Claude,
758            Mode::Auto,
759            PathBuf::from("/repo"),
760        );
761        state.verification_baseline_captured = true;
762        let json = serde_json::to_string(&state).unwrap();
763        assert!(
764            json.contains("verification_baseline_captured"),
765            "verification_baseline_captured must appear in persisted JSON"
766        );
767        let loaded: State = serde_json::from_str(&json).unwrap();
768        assert!(
769            loaded.verification_baseline_captured,
770            "a captured baseline must survive the save/load the real pipeline performs"
771        );
772    }
773
774    /// 35.2 D-01: verification_run_nonce must survive the save/load cycle
775    /// `handle_validate_outcome` → `select_loop_back_fix` performs.
776    #[test]
777    fn verification_run_nonce_round_trips_through_serde() {
778        let mut state = State::new(
779            PhaseId::new(1),
780            AgentKind::Claude,
781            Mode::Auto,
782            PathBuf::from("/repo"),
783        );
784        state.verification_run_nonce = Some(42);
785        let json = serde_json::to_string(&state).unwrap();
786        assert!(
787            json.contains("verification_run_nonce"),
788            "verification_run_nonce must appear in persisted JSON"
789        );
790        let loaded: State = serde_json::from_str(&json).unwrap();
791        assert_eq!(
792            loaded.verification_run_nonce,
793            Some(42),
794            "verification_run_nonce must round-trip through serde"
795        );
796    }
797
798    /// 35.2 D-01: a serde-absent verification_run_nonce (state written by
799    /// a pre-35.2 binary) deserializes to None — the conservative direction.
800    #[test]
801    fn verification_run_nonce_absent_from_json_defaults_to_none() {
802        let json = r#"{
803            "stage": "code",
804            "phase": 1,
805            "agent": "claude",
806            "mode": "auto",
807            "started_at": "0",
808            "project_root": "/repo"
809        }"#;
810        let loaded: State = serde_json::from_str(json).unwrap();
811        assert_eq!(
812            loaded.verification_run_nonce, None,
813            "pre-35.2 state must default to None — the conservative provenance reading"
814        );
815    }
816
817    /// D-18f: `preflight_retries` round-trips through serde (its own key
818    /// appears in the persisted JSON) — the wedge this counter bounds spans
819    /// separate `devflow` invocations, so it must survive a save/load
820    /// cycle, not just live in memory — and a serde-absent value (state
821    /// written by a pre-18f binary) deserializes to 0, not a hard error.
822    #[test]
823    fn preflight_retries_round_trips_through_serde() {
824        let mut state = State::new(
825            PhaseId::new(1),
826            AgentKind::Claude,
827            Mode::Auto,
828            PathBuf::from("/repo"),
829        );
830        state.preflight_retries = 2;
831        let json = serde_json::to_string(&state).unwrap();
832        assert!(
833            json.contains("preflight_retries"),
834            "preflight_retries must appear in persisted JSON"
835        );
836        let loaded: State = serde_json::from_str(&json).unwrap();
837        assert_eq!(
838            loaded.preflight_retries, 2,
839            "preflight_retries must round-trip through serde"
840        );
841
842        let absent_json = r#"{
843            "stage": "code",
844            "phase": 1,
845            "agent": "claude",
846            "mode": "auto",
847            "started_at": "0",
848            "project_root": "/repo"
849        }"#;
850        let loaded_absent: State = serde_json::from_str(absent_json).unwrap();
851        assert_eq!(loaded_absent.preflight_retries, 0);
852    }
853
854    /// `monitor_pid` round-trips through serde as an exact `u32` (18b).
855    #[test]
856    fn monitor_pid_round_trips_through_serde() {
857        let mut state = State::new(
858            PhaseId::new(1),
859            AgentKind::Claude,
860            Mode::Auto,
861            PathBuf::from("/repo"),
862        );
863        state.monitor_pid = Some(4242);
864        let json = serde_json::to_string(&state).unwrap();
865        assert!(
866            json.contains("monitor_pid"),
867            "monitor_pid must appear in persisted JSON"
868        );
869        let loaded: State = serde_json::from_str(&json).unwrap();
870        assert_eq!(
871            loaded.monitor_pid,
872            Some(4242),
873            "monitor_pid must round-trip through serde"
874        );
875    }
876
877    /// A serde-absent `monitor_pid` (state written by a pre-18b binary) must
878    /// deserialize to `None`, not `Some(0)` — a `Some(0)` default would let a
879    /// pre-18b state file render as a monitor at pid 0.
880    #[test]
881    fn monitor_pid_absent_from_json_defaults_to_none() {
882        let json = r#"{
883            "stage": "code",
884            "phase": 1,
885            "agent": "claude",
886            "mode": "auto",
887            "started_at": "0",
888            "project_root": "/repo"
889        }"#;
890        let loaded: State = serde_json::from_str(json).unwrap();
891        assert_eq!(loaded.monitor_pid, None);
892    }
893
894    /// `session_id` round-trips through serde as an exact `Option<String>`
895    /// (D-04, 28-02) — mirrors the `monitor_pid` pair above.
896    #[test]
897    fn session_id_round_trips_through_serde() {
898        let mut state = State::new(
899            PhaseId::new(1),
900            AgentKind::Claude,
901            Mode::Auto,
902            PathBuf::from("/repo"),
903        );
904        state.session_id = Some("cf29bfec-69e8-45df-a4f3-3da08ab6f66e".to_string());
905        let json = serde_json::to_string(&state).unwrap();
906        assert!(
907            json.contains("session_id"),
908            "session_id must appear in persisted JSON"
909        );
910        let loaded: State = serde_json::from_str(&json).unwrap();
911        assert_eq!(
912            loaded.session_id.as_deref(),
913            Some("cf29bfec-69e8-45df-a4f3-3da08ab6f66e"),
914            "session_id must round-trip through serde"
915        );
916    }
917
918    /// A serde-absent `session_id` (state written by a pre-28-02 binary) must
919    /// deserialize to `None`, not fail to deserialize.
920    #[test]
921    fn session_id_absent_from_json_defaults_to_none() {
922        let json = r#"{
923            "stage": "code",
924            "phase": 1,
925            "agent": "claude",
926            "mode": "auto",
927            "started_at": "0",
928            "project_root": "/repo"
929        }"#;
930        let loaded: State = serde_json::from_str(json).unwrap();
931        assert_eq!(loaded.session_id, None);
932    }
933
934    /// `checkpoint_resumes` round-trips through serde as an exact `u32`
935    /// (D-04, 28-02).
936    #[test]
937    fn checkpoint_resumes_round_trips_through_serde() {
938        let mut state = State::new(
939            PhaseId::new(1),
940            AgentKind::Claude,
941            Mode::Auto,
942            PathBuf::from("/repo"),
943        );
944        state.checkpoint_resumes = 2;
945        let json = serde_json::to_string(&state).unwrap();
946        assert!(
947            json.contains("checkpoint_resumes"),
948            "checkpoint_resumes must appear in persisted JSON"
949        );
950        let loaded: State = serde_json::from_str(&json).unwrap();
951        assert_eq!(
952            loaded.checkpoint_resumes, 2,
953            "checkpoint_resumes must round-trip through serde"
954        );
955    }
956
957    /// A serde-absent `checkpoint_resumes` (state written by a pre-28-02
958    /// binary) must deserialize to `0`, not fail to deserialize.
959    #[test]
960    fn checkpoint_resumes_absent_from_json_defaults_to_zero() {
961        let json = r#"{
962            "stage": "code",
963            "phase": 1,
964            "agent": "claude",
965            "mode": "auto",
966            "started_at": "0",
967            "project_root": "/repo"
968        }"#;
969        let loaded: State = serde_json::from_str(json).unwrap();
970        assert_eq!(loaded.checkpoint_resumes, 0);
971    }
972
973    /// 23-09 Task 1: `yes_ship` round-trips through serde as an exact `bool`
974    /// — its own key appears in the persisted JSON, and a fresh deserialize
975    /// recovers the value set, mirroring the `monitor_pid` pair above.
976    #[test]
977    fn yes_ship_round_trips_through_serde() {
978        let mut state = State::new(
979            PhaseId::new(1),
980            AgentKind::Claude,
981            Mode::Auto,
982            PathBuf::from("/repo"),
983        );
984        state.yes_ship = true;
985        let json = serde_json::to_string(&state).unwrap();
986        assert!(
987            json.contains("yes_ship"),
988            "yes_ship must appear in persisted JSON"
989        );
990        let loaded: State = serde_json::from_str(&json).unwrap();
991        assert!(loaded.yes_ship, "yes_ship must round-trip through serde");
992    }
993
994    /// A serde-absent `yes_ship` (state written by a pre-23-09 binary) must
995    /// deserialize to `false`, not fail to deserialize — the same
996    /// backward-compat pattern as every other `#[serde(default)]` field
997    /// added since 17-01.
998    #[test]
999    fn yes_ship_absent_from_json_defaults_to_false() {
1000        let json = r#"{
1001            "stage": "code",
1002            "phase": 1,
1003            "agent": "claude",
1004            "mode": "auto",
1005            "started_at": "0",
1006            "project_root": "/repo"
1007        }"#;
1008        let loaded: State = serde_json::from_str(json).unwrap();
1009        assert!(!loaded.yes_ship);
1010    }
1011
1012    /// 20c: `stop_until`/`stopped`/`stop_reason` all round-trip through
1013    /// serde — each field's own key appears in the persisted JSON, and a
1014    /// fresh deserialize recovers the exact values set.
1015    #[test]
1016    fn stop_fields_round_trip_through_serde() {
1017        let mut state = State::new(
1018            PhaseId::new(1),
1019            AgentKind::Claude,
1020            Mode::Auto,
1021            PathBuf::from("/repo"),
1022        );
1023        state.stop_until = Some(Stage::Plan);
1024        state.stopped = true;
1025        state.stop_reason = Some("stopped after plan completed (--until plan)".to_string());
1026        let json = serde_json::to_string(&state).unwrap();
1027        assert!(
1028            json.contains("stop_until") && json.contains("stopped") && json.contains("stop_reason"),
1029            "all three stop fields must appear in persisted JSON: {json}"
1030        );
1031        let loaded: State = serde_json::from_str(&json).unwrap();
1032        assert_eq!(
1033            loaded.stop_until,
1034            Some(Stage::Plan),
1035            "stop_until must round-trip through serde"
1036        );
1037        assert!(loaded.stopped, "stopped must round-trip through serde");
1038        assert_eq!(
1039            loaded.stop_reason.as_deref(),
1040            Some("stopped after plan completed (--until plan)"),
1041            "stop_reason must round-trip through serde"
1042        );
1043    }
1044
1045    /// A serde-absent `stop_until`/`stopped`/`stop_reason` (state written by
1046    /// a pre-20c binary) must default to `None`/`false`/`None`, not fail to
1047    /// deserialize — the same backward-compat pattern as every other
1048    /// `#[serde(default)]` field added since 17-01.
1049    #[test]
1050    fn stop_fields_absent_from_json_default() {
1051        let json = r#"{
1052            "stage": "code",
1053            "phase": 1,
1054            "agent": "claude",
1055            "mode": "auto",
1056            "started_at": "0",
1057            "project_root": "/repo"
1058        }"#;
1059        let loaded: State = serde_json::from_str(json).unwrap();
1060        assert_eq!(loaded.stop_until, None);
1061        assert!(!loaded.stopped);
1062        assert_eq!(loaded.stop_reason, None);
1063    }
1064}