agengo 0.4.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Typed view of a validated plan.
//!
//! `contract::validate_plan` checks a plan document and normalizes it to
//! JSON. These types read that normalized form, so the rest of the program
//! gets compile-time field names instead of string keys. Serializing a
//! `Plan` gives back the same JSON, which is what the state database and the
//! agent requests store.

use anyhow::{Context, Result};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

/// A command and its arguments, run without a shell.
pub type Argv = Vec<String>;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Plan {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_version: Option<u64>,
    pub goal: String,
    pub tasks: Vec<Task>,
    #[serde(default)]
    pub setup: Vec<Argv>,
    #[serde(default)]
    pub integration_verify: Vec<Argv>,
    pub final_verify: Vec<Argv>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality: Option<Quality>,
    /// The approved spec this plan implements (see `agengo spec`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spec: Option<SpecRef>,
    /// Choices the planner made that the goal, spec and principles left
    /// open, for the person approving the plan. They do not change the run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assumptions: Vec<Assumption>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Assumption {
    pub text: String,
    pub impact: String,
    pub if_wrong: String,
}

/// The spec file a plan was drafted from, the digest it was approved with,
/// and the user stories the plan covers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SpecRef {
    pub path: String,
    pub digest: String,
    pub stories: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Task {
    pub id: String,
    pub goal: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default)]
    pub depends: Vec<String>,
    pub owns: Vec<String>,
    pub acceptance: Vec<Acceptance>,
    #[serde(default)]
    pub setup: Vec<Argv>,
    pub verify: Vec<Argv>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependency_context: Vec<DependencyContext>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub related_to: Vec<Related>,
}

/// An acceptance criterion as written in the plan: plain text gets the id
/// `AC-<position>`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Acceptance {
    Text(String),
    Item {
        id: String,
        text: String,
        /// Spec requirements (`FR-n`) and success criteria (`SC-n`) this
        /// criterion checks.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        refs: Vec<String>,
    },
}

/// An acceptance criterion with its resolved id.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Criterion {
    pub id: String,
    pub text: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DependencyContext {
    pub task_id: String,
    pub needed_for: String,
    #[serde(default)]
    pub refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Related {
    pub task_id: String,
    pub reason: String,
    #[serde(default)]
    pub refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Quality {
    #[serde(default, deserialize_with = "duplicate_mode")]
    pub python_duplicates: DuplicateMode,
    #[serde(default)]
    pub ignore_paths: Vec<String>,
    #[serde(default)]
    pub checks: Vec<Argv>,
    #[serde(default)]
    pub review: bool,
    /// Have a verifier try to refute each blocking review finding before the
    /// task goes back to the Builder.
    #[serde(default)]
    pub verify_findings: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DuplicateMode {
    Off,
    #[default]
    Warn,
    Block,
}

/// Plans stored by 0.2.x may hold `true` (block) or `false` (off).
fn duplicate_mode<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DuplicateMode, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Stored {
        Legacy(bool),
        Mode(DuplicateMode),
    }
    Ok(match Stored::deserialize(deserializer)? {
        Stored::Legacy(true) => DuplicateMode::Block,
        Stored::Legacy(false) => DuplicateMode::Off,
        Stored::Mode(mode) => mode,
    })
}

impl Plan {
    /// Read a plan normalized by `contract::validate_plan` or stored by an
    /// earlier run.
    pub fn from_value(value: Value) -> Result<Self> {
        serde_json::from_value(value).context("stored plan does not match the plan format")
    }

    pub fn to_value(&self) -> Value {
        serde_json::to_value(self).expect("a plan always serializes to JSON")
    }

    /// The task with this id. The run's task rows mirror the plan, so a
    /// missing id means the state database and the plan disagree.
    pub fn task(&self, id: &str) -> Result<&Task> {
        self.tasks
            .iter()
            .find(|task| task.id == id)
            .with_context(|| format!("task {id} is not in the current plan"))
    }

    /// The quality policy, with defaults when the plan sets none.
    pub fn quality(&self) -> Quality {
        self.quality.clone().unwrap_or_default()
    }
}

impl Task {
    pub fn title(&self) -> &str {
        self.title.as_deref().unwrap_or(&self.goal)
    }

    pub fn criteria(&self) -> Vec<Criterion> {
        self.acceptance
            .iter()
            .enumerate()
            .map(|(index, item)| match item {
                Acceptance::Text(text) => Criterion {
                    id: format!("AC-{}", index + 1),
                    text: text.clone(),
                    refs: Vec::new(),
                },
                Acceptance::Item { id, text, refs } => Criterion {
                    id: id.clone(),
                    text: text.clone(),
                    refs: refs.clone(),
                },
            })
            .collect()
    }

    pub fn depends_on(&self, id: &str) -> bool {
        self.depends.iter().any(|dep| dep == id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contract::validate_plan;
    use serde_json::json;

    fn full_plan() -> Value {
        json!({
            "schema_version": 1,
            "goal": "Ship",
            "setup": [["npm", "ci"]],
            "integration_verify": [["make", "check"]],
            "final_verify": [["make", "test"]],
            "quality": {"python_duplicates": true, "ignore_paths": ["vendor"]},
            "tasks": [
                {"id": "a", "goal": "Build A", "title": "A", "owns": ["src/a"],
                 "acceptance": ["Works", {"id": "AC-X", "text": "Fast"}],
                 "setup": [["true"]], "verify": [["test", "-d", "src/a"]]},
                {"id": "b", "goal": "Build B", "owns": ["src/b"], "depends": ["a"],
                 "acceptance": ["Works"], "verify": [["true"]],
                 "dependency_context": [{"task_id": "a", "needed_for": "API", "refs": ["src/a/api.rs"]}]},
                {"id": "c", "goal": "Build C", "owns": ["src/c"], "acceptance": ["Works"],
                 "verify": [["true"]], "related_to": [{"task_id": "a", "reason": "Same style"}]}
            ]
        })
    }

    #[test]
    fn typed_plan_round_trips_the_normalized_json() -> Result<()> {
        for raw in [
            full_plan(),
            json!({"goal": "Small", "final_verify": [["true"]], "tasks": [
                {"id": "only", "goal": "One", "owns": ["x"], "acceptance": ["Done"], "verify": [["true"]]}
            ]}),
        ] {
            let normalized = validate_plan(raw)?;
            let plan = Plan::from_value(normalized.clone())?;
            assert_eq!(plan.to_value(), normalized);
        }
        Ok(())
    }

    #[test]
    fn criteria_quality_and_lookups() -> Result<()> {
        let plan = Plan::from_value(validate_plan(full_plan())?)?;
        let a = plan.task("a")?;
        assert_eq!(a.title(), "A");
        assert_eq!(plan.task("b")?.title(), "Build B");
        assert!(plan.task("missing").is_err());
        assert_eq!(
            a.criteria(),
            vec![
                Criterion {
                    id: "AC-1".into(),
                    text: "Works".into(),
                    refs: Vec::new(),
                },
                Criterion {
                    id: "AC-X".into(),
                    text: "Fast".into(),
                    refs: Vec::new(),
                },
            ]
        );
        assert!(plan.task("b")?.depends_on("a"));
        let quality = plan.quality();
        assert_eq!(quality.python_duplicates, DuplicateMode::Block);
        assert_eq!(quality.ignore_paths, ["vendor"]);
        assert_eq!(
            Plan::from_value(json!({"goal":"g","final_verify":[["true"]],"tasks":[]}))?.quality(),
            Quality::default()
        );
        Ok(())
    }

    #[test]
    fn stored_legacy_duplicate_flags_are_read() -> Result<()> {
        let quality: Quality = serde_json::from_value(json!({"python_duplicates": false}))?;
        assert_eq!(quality.python_duplicates, DuplicateMode::Off);
        assert!(serde_json::from_value::<Quality>(json!({"python_duplicates": "maybe"})).is_err());
        Ok(())
    }
}