agengo 0.5.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
use super::*;

/// The last draft that `agengo plan --spec` returned with questions, kept in
/// the state directory per spec and story selection. The next draft from the
/// same spec revises it with the decisions recorded since, instead of
/// starting over and possibly asking something new.
pub struct Drafts {
    pub(super) file: PathBuf,
    spec: String,
    stories: Vec<String>,
}

/// How long a kept draft stays usable: about a week, longer than a planner
/// question normally waits for its answer.
pub(super) const DRAFT_MAX_AGE: u64 = 7 * 24 * 60 * 60;

pub(super) fn now_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_secs())
}

impl Drafts {
    pub fn new(repo: &Repo, stored_path: &str, stories: &[String]) -> Self {
        let key = format!("{stored_path}\n{}", stories.join(","));
        let hash = Sha256::digest(key.as_bytes());
        let name: String = hash[..8].iter().map(|byte| format!("{byte:02x}")).collect();
        Self {
            file: repo.data.join("drafts").join(format!("{name}.json")),
            spec: stored_path.to_owned(),
            stories: stories.to_vec(),
        }
    }

    /// The kept draft for the planner, with the decisions the spec recorded
    /// after it, or `None` when there is no usable draft or no decision since.
    /// The draft is only a cache: one that cannot be read, belongs to another
    /// selection or is older than `DRAFT_MAX_AGE` is ignored, never an error.
    pub fn previous(&self, spec: &Value) -> Result<Option<Value>> {
        let text = match fs::read_to_string(&self.file) {
            Ok(text) => text,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => {
                eprintln!(
                    "agengo: warning: ignoring the kept draft {}: {error}",
                    self.file.display()
                );
                return Ok(None);
            }
        };
        let kept: Value = match serde_json::from_str(&text) {
            Ok(kept) => kept,
            Err(error) => {
                eprintln!(
                    "agengo: warning: ignoring the kept draft {}: {error}",
                    self.file.display()
                );
                return Ok(None);
            }
        };
        if kept["spec"] != json!(self.spec) || kept["stories"] != json!(self.stories) {
            return Ok(None);
        }
        // An exchange left unfinished for long is not the one being resumed.
        let saved = kept["saved_at"].as_u64().unwrap_or(0);
        if now_seconds().saturating_sub(saved) > DRAFT_MAX_AGE {
            return Ok(None);
        }
        let since = kept["round"].as_u64().unwrap_or(0);
        let decisions: Vec<Value> = array_or_empty(&spec["clarifications"])
            .iter()
            .filter(|item| item["round"].as_u64().is_some_and(|round| round > since))
            .map(|item| {
                if item["question"] == DECISION {
                    json!({"answer": item["answer"]})
                } else {
                    json!({"question": item["question"], "answer": item["answer"]})
                }
            })
            .collect();
        if decisions.is_empty() {
            return Ok(None);
        }
        Ok(Some(json!({
            "tasks": kept["tasks"], "questions": kept["questions"], "decisions": decisions,
        })))
    }

    /// Keeps a draft that still has questions; `round` is the spec round it
    /// was drafted from.
    pub fn remember(&self, draft: &Value, round: &Value) -> Result<()> {
        let parent = self.file.parent().context("draft path has no parent")?;
        fs::create_dir_all(parent)
            .with_context(|| format!("cannot create {}", parent.display()))?;
        let kept = json!({
            "spec": self.spec, "stories": self.stories, "round": round,
            "saved_at": now_seconds(),
            "tasks": draft["tasks"], "questions": draft["questions"],
        });
        // Write next to the target and rename, so an interrupted write never
        // leaves a truncated draft behind.
        let mut file = tempfile::NamedTempFile::new_in(parent)?;
        file.write_all(&serde_json::to_vec_pretty(&kept)?)?;
        file.persist(&self.file)
            .with_context(|| format!("cannot write {}", self.file.display()))?;
        Ok(())
    }

    /// Drops the kept draft once a complete plan exists.
    pub fn forget(&self) -> Result<()> {
        match fs::remove_file(&self.file) {
            Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
                Err(error).with_context(|| format!("cannot remove {}", self.file.display()))
            }
            _ => Ok(()),
        }
    }
}