Skip to main content

plan_issue/tracking/
run_state.rs

1//! Typed local run-state for `plan-issue tracking`.
2//!
3//! Schema identifier: `plan-issue.execution-run.v1`. File layout under the
4//! existing state-dir contract is documented in
5//! `docs/source/plan-issue-redesign/plan-tracking-issue-run-state-controller-v1.md`.
6
7use std::collections::BTreeMap;
8use std::fs;
9use std::io;
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15use crate::runtime_layout::{self, IssueRoot};
16
17/// Stable schema identifier embedded in every `run-state.json` document.
18pub const RUN_STATE_SCHEMA: &str = "plan-issue.execution-run.v1";
19
20const RUNS_DIR: &str = "runs";
21const RUN_STATE_FILE: &str = "run-state.json";
22const EVENTS_FILE: &str = "events.jsonl";
23const INPUTS_DIR: &str = "inputs";
24const RENDERED_DIR: &str = "rendered";
25const ARTIFACTS_DIR: &str = "artifacts";
26
27/// High-level execution phase. Maps onto FSM states but stays human-friendly.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum RunPhase {
31    Initial,
32    Implementing,
33    Validating,
34    Reviewing,
35    Blocked,
36    ReadyForClose,
37    Closed,
38}
39
40impl RunPhase {
41    pub fn as_str(self) -> &'static str {
42        match self {
43            Self::Initial => "initial",
44            Self::Implementing => "implementing",
45            Self::Validating => "validating",
46            Self::Reviewing => "reviewing",
47            Self::Blocked => "blocked",
48            Self::ReadyForClose => "ready_for_close",
49            Self::Closed => "closed",
50        }
51    }
52}
53
54/// Selected scope (sprint, task, title) recorded in the run.
55#[derive(Debug, Clone, Default, Serialize, Deserialize)]
56pub struct SelectedScope {
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub sprint: Option<i32>,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub task: Option<String>,
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub title: Option<String>,
63}
64
65/// Linked PR reference captured in the run state.
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct LinkedPr {
68    #[serde(rename = "ref")]
69    pub r#ref: String,
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub url: Option<String>,
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub status: Option<String>,
74}
75
76/// Compact validation summary captured in run state.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct ValidationSummary {
79    pub overall: String,
80    #[serde(default, skip_serializing_if = "Vec::is_empty")]
81    pub commands: Vec<ValidationCommandRow>,
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub waiver: Option<String>,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub evidence_path: Option<PathBuf>,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct ValidationCommandRow {
90    pub command: String,
91    pub status: String,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub evidence: Option<String>,
94}
95
96/// Compact review summary captured in run state.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct ReviewSummary {
99    pub decision: String,
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub findings_disposition: Vec<String>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub evidence: Option<String>,
104}
105
106/// Captured reconciliation snapshot from a prior FSM evaluation.
107#[derive(Debug, Clone, Default, Serialize, Deserialize)]
108pub struct LastReconciled {
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub at: Option<String>,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub fsm_state: Option<String>,
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub dashboard_status: Option<String>,
115    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
116    pub latest_comments: BTreeMap<String, String>,
117}
118
119/// Pending transition the controller will perform next.
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct PendingTransition {
122    pub kind: String,
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub reason: Option<String>,
125}
126
127/// Typed run state document persisted as `run-state.json`.
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct ExecutionRun {
130    pub schema: String,
131    pub run_id: String,
132    pub repo: String,
133    pub issue: u64,
134    pub profile: String,
135    pub phase: RunPhase,
136    pub created_at: String,
137    pub updated_at: String,
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub bundle: Option<PathBuf>,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub execution_state_file: Option<PathBuf>,
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub selected_scope: Option<SelectedScope>,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub branch: Option<String>,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub worktree: Option<PathBuf>,
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub pr: Option<LinkedPr>,
150    /// Every linked PR observed across the run, accumulated in first-seen
151    /// order (dedup by ref). `pr` stays the current / most-recent lane PR;
152    /// `linked_prs` lets a dispatch dashboard name *every* lane PR instead of
153    /// only the latest. `#[serde(default)]` keeps older run states readable.
154    #[serde(default, skip_serializing_if = "Vec::is_empty")]
155    pub linked_prs: Vec<LinkedPr>,
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub last_reconciled: Option<LastReconciled>,
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub pending_transition: Option<PendingTransition>,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub validation: Option<ValidationSummary>,
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub review: Option<ReviewSummary>,
164    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
165    pub artifacts: BTreeMap<String, String>,
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub notes: Vec<String>,
168    /// Free-form extra fields kept around so future schema additions do not
169    /// silently drop on read/write round-trip.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub extra: Option<Value>,
172}
173
174impl ExecutionRun {
175    pub fn new(
176        run_id: impl Into<String>,
177        repo: impl Into<String>,
178        issue: u64,
179        profile: impl Into<String>,
180        phase: RunPhase,
181        at: impl Into<String>,
182    ) -> Self {
183        let at = at.into();
184        Self {
185            schema: RUN_STATE_SCHEMA.to_string(),
186            run_id: run_id.into(),
187            repo: repo.into(),
188            issue,
189            profile: profile.into(),
190            phase,
191            created_at: at.clone(),
192            updated_at: at,
193            bundle: None,
194            execution_state_file: None,
195            selected_scope: None,
196            branch: None,
197            worktree: None,
198            pr: None,
199            linked_prs: Vec::new(),
200            last_reconciled: None,
201            pending_transition: None,
202            validation: None,
203            review: None,
204            artifacts: BTreeMap::new(),
205            notes: Vec::new(),
206            extra: None,
207        }
208    }
209
210    /// Record the current linked PR and accumulate it into `linked_prs`
211    /// (dedup by ref, first-seen order). `pr` tracks the most-recent lane PR
212    /// for backward compatibility; `linked_prs` retains every lane PR so the
213    /// dispatch dashboard can name them all, not just the latest.
214    pub fn set_linked_pr(&mut self, pr: LinkedPr) {
215        if !self
216            .linked_prs
217            .iter()
218            .any(|existing| existing.r#ref == pr.r#ref)
219        {
220            self.linked_prs.push(pr.clone());
221        }
222        self.pr = Some(pr);
223    }
224}
225
226/// Validation errors emitted by [`parse_run_state`].
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub enum RunStateError {
229    SchemaMismatch { actual: String },
230    MissingField(&'static str),
231    Malformed(String),
232}
233
234impl std::fmt::Display for RunStateError {
235    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        match self {
237            Self::SchemaMismatch { actual } => write!(
238                f,
239                "run-state.json schema mismatch: expected {RUN_STATE_SCHEMA}, got {actual}"
240            ),
241            Self::MissingField(name) => write!(f, "run-state.json missing required field `{name}`"),
242            Self::Malformed(msg) => write!(f, "run-state.json malformed: {msg}"),
243        }
244    }
245}
246
247impl std::error::Error for RunStateError {}
248
249/// Parse a `run-state.json` body and validate the schema id and required
250/// fields.
251pub fn parse_run_state(raw: &str) -> Result<ExecutionRun, RunStateError> {
252    let value: Value = serde_json::from_str(raw)
253        .map_err(|err| RunStateError::Malformed(format!("failed to parse JSON: {err}")))?;
254    let schema = value
255        .get("schema")
256        .and_then(Value::as_str)
257        .ok_or(RunStateError::MissingField("schema"))?;
258    if schema != RUN_STATE_SCHEMA {
259        return Err(RunStateError::SchemaMismatch {
260            actual: schema.to_string(),
261        });
262    }
263    for required in [
264        "run_id",
265        "repo",
266        "issue",
267        "profile",
268        "phase",
269        "created_at",
270        "updated_at",
271    ] {
272        if value.get(required).is_none() {
273            return Err(RunStateError::MissingField(name_for(required)));
274        }
275    }
276    serde_json::from_value::<ExecutionRun>(value)
277        .map_err(|err| RunStateError::Malformed(err.to_string()))
278}
279
280fn name_for(field: &str) -> &'static str {
281    match field {
282        "run_id" => "run_id",
283        "repo" => "repo",
284        "issue" => "issue",
285        "profile" => "profile",
286        "phase" => "phase",
287        "created_at" => "created_at",
288        "updated_at" => "updated_at",
289        _ => "unknown",
290    }
291}
292
293/// Serialize an [`ExecutionRun`] to canonical JSON.
294pub fn render_run_state(run: &ExecutionRun) -> Result<String, RunStateError> {
295    serde_json::to_string_pretty(run).map_err(|err| RunStateError::Malformed(err.to_string()))
296}
297
298/// Read `run-state.json` from disk.
299pub fn read_run_state(path: &Path) -> io::Result<ExecutionRun> {
300    let raw = fs::read_to_string(path)?;
301    parse_run_state(&raw).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
302}
303
304/// Write `run-state.json` to disk. Creates parent directories as needed.
305pub fn write_run_state(path: &Path, run: &ExecutionRun) -> io::Result<()> {
306    if let Some(parent) = path.parent() {
307        runtime_layout::ensure_dir(parent)?;
308    }
309    let rendered =
310        render_run_state(run).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
311    fs::write(path, rendered)
312}
313
314/// Issue-scoped run root rooted under the existing
315/// [`crate::runtime_layout::IssueRoot`] contract.
316#[derive(Debug, Clone)]
317pub struct RunRoot {
318    issue_root: IssueRoot,
319    run_id: String,
320}
321
322impl RunRoot {
323    /// Build the run root under `<issue-root>/runs/<run-id>/`.
324    pub fn new(
325        repo_slug: &str,
326        issue_number: u64,
327        run_id: impl Into<String>,
328    ) -> Result<Self, runtime_layout::RuntimeLayoutError> {
329        let issue_root = IssueRoot::new(repo_slug, issue_number)?;
330        Ok(Self {
331            issue_root,
332            run_id: run_id.into(),
333        })
334    }
335
336    pub fn issue_root(&self) -> &IssueRoot {
337        &self.issue_root
338    }
339
340    pub fn run_id(&self) -> &str {
341        &self.run_id
342    }
343
344    pub fn root(&self) -> PathBuf {
345        self.issue_root.root().join(RUNS_DIR).join(&self.run_id)
346    }
347
348    pub fn run_state_path(&self) -> PathBuf {
349        self.root().join(RUN_STATE_FILE)
350    }
351
352    pub fn events_path(&self) -> PathBuf {
353        self.root().join(EVENTS_FILE)
354    }
355
356    pub fn inputs_dir(&self) -> PathBuf {
357        self.root().join(INPUTS_DIR)
358    }
359
360    pub fn rendered_dir(&self) -> PathBuf {
361        self.root().join(RENDERED_DIR)
362    }
363
364    pub fn artifacts_dir(&self) -> PathBuf {
365        self.root().join(ARTIFACTS_DIR)
366    }
367
368    /// Ensure the full directory tree exists.
369    pub fn ensure_layout(&self) -> io::Result<()> {
370        runtime_layout::ensure_dir(&self.root())?;
371        runtime_layout::ensure_dir(&self.inputs_dir())?;
372        runtime_layout::ensure_dir(&self.rendered_dir())?;
373        runtime_layout::ensure_dir(&self.artifacts_dir())?;
374        Ok(())
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381    use serde_json::json;
382
383    #[test]
384    fn tracking_run_state_round_trips_required_and_recommended_fields() {
385        let mut run = ExecutionRun::new(
386            "20260526-150405-issue-123",
387            "owner/repo",
388            123,
389            "tracking",
390            RunPhase::Implementing,
391            "2026-05-26T15:04:05Z",
392        );
393        run.bundle = Some(PathBuf::from("docs/plans/example"));
394        run.execution_state_file = Some(PathBuf::from(
395            "docs/plans/example/example-execution-state.md",
396        ));
397        run.selected_scope = Some(SelectedScope {
398            sprint: Some(1),
399            task: Some("1.2".to_string()),
400            title: Some("visible lint".to_string()),
401        });
402        run.branch = Some("feat/x".to_string());
403        run.pr = Some(LinkedPr {
404            r#ref: "owner/repo#456".to_string(),
405            url: Some("https://example.com/pr/456".to_string()),
406            status: Some("open".to_string()),
407        });
408        run.validation = Some(ValidationSummary {
409            overall: "pass".to_string(),
410            commands: vec![ValidationCommandRow {
411                command: "cargo test".to_string(),
412                status: "pass".to_string(),
413                evidence: Some("log.txt".to_string()),
414            }],
415            waiver: None,
416            evidence_path: None,
417        });
418        let rendered = render_run_state(&run).expect("render");
419        let parsed = parse_run_state(&rendered).expect("parse");
420        assert_eq!(parsed.run_id, run.run_id);
421        assert_eq!(parsed.repo, run.repo);
422        assert_eq!(parsed.issue, run.issue);
423        assert_eq!(parsed.phase, run.phase);
424        assert_eq!(
425            parsed.selected_scope.as_ref().and_then(|s| s.task.clone()),
426            Some("1.2".to_string())
427        );
428        assert_eq!(
429            parsed.validation.as_ref().map(|v| v.overall.clone()),
430            Some("pass".to_string())
431        );
432    }
433
434    #[test]
435    fn tracking_run_state_rejects_wrong_schema() {
436        let raw = json!({
437            "schema": "wrong.schema.v1",
438            "run_id": "x",
439            "repo": "o/r",
440            "issue": 1,
441            "profile": "tracking",
442            "phase": "initial",
443            "created_at": "x",
444            "updated_at": "x"
445        })
446        .to_string();
447        match parse_run_state(&raw) {
448            Err(RunStateError::SchemaMismatch { actual }) => assert_eq!(actual, "wrong.schema.v1"),
449            other => panic!("expected SchemaMismatch, got {other:?}"),
450        }
451    }
452
453    #[test]
454    fn tracking_run_state_rejects_missing_required_field() {
455        let raw = json!({
456            "schema": RUN_STATE_SCHEMA,
457            "run_id": "x",
458            "issue": 1,
459            "profile": "tracking",
460            "phase": "initial",
461            "created_at": "x",
462            "updated_at": "x"
463        })
464        .to_string();
465        match parse_run_state(&raw) {
466            Err(RunStateError::MissingField("repo")) => {}
467            other => panic!("expected MissingField(repo), got {other:?}"),
468        }
469    }
470
471    #[test]
472    fn tracking_run_state_runroot_layout_under_state_dir() {
473        let runroot = RunRoot::new("owner__repo", 123, "20260526-run-1").expect("runroot");
474        let expected_root_suffix = "owner__repo/issue-123/runs/20260526-run-1";
475        assert!(
476            runroot
477                .root()
478                .to_string_lossy()
479                .ends_with(expected_root_suffix),
480            "runroot suffix drift: {}",
481            runroot.root().display()
482        );
483        assert!(
484            runroot
485                .run_state_path()
486                .to_string_lossy()
487                .ends_with("runs/20260526-run-1/run-state.json")
488        );
489        assert!(
490            runroot
491                .events_path()
492                .to_string_lossy()
493                .ends_with("runs/20260526-run-1/events.jsonl")
494        );
495    }
496}