agengo 0.5.4

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

/// How a plan names its spec: relative to the repository root when the file
/// is inside it, so the plan works from any checkout.
pub fn stored_path(path: &Path, root: &Path) -> Result<String> {
    let absolute =
        fs::canonicalize(path).with_context(|| format!("cannot read {}", path.display()))?;
    let root = fs::canonicalize(root)?;
    Ok(match absolute.strip_prefix(&root) {
        Ok(relative) => relative
            .components()
            .map(|part| part.as_os_str().to_string_lossy())
            .collect::<Vec<_>>()
            .join("/"),
        Err(_) => absolute.display().to_string(),
    })
}

/// Checks a plan against the spec it names (rules C0–C4) and returns the
/// spec with the warnings, or `None` for a plan without a spec. C0–C2 are
/// errors: the spec must be the approved version the plan was drafted from,
/// every reference must exist, and every requirement of the chosen stories
/// must be checked by some acceptance criterion.
pub fn coverage(plan: &Plan, root: &Path) -> Result<Option<(Value, Vec<String>)>> {
    let Some(reference) = &plan.spec else {
        return Ok(None);
    };
    // A path inside the repository is stored relative; refuse one that climbs
    // out with `..`. An absolute path is how `stored_path` names a spec that
    // lives outside the repository.
    if !Path::new(&reference.path).is_absolute() {
        crate::contract::scope_path(&reference.path)
            .with_context(|| format!("plan spec path {:?}", reference.path))?;
    }
    let path = root.join(&reference.path);
    let spec = load(&path)?;
    if !approved(&spec) {
        bail!(
            "C0: {} is not approved or changed after approval; approve it with agengo spec {} --approve and draft the plan again",
            path.display(),
            path.display()
        );
    }
    if spec["approved"]["digest"] != reference.digest.as_str() {
        bail!(
            "C0: the plan was drafted from another version of {}; draft it again with agengo plan --spec",
            path.display()
        );
    }
    let stories = chosen(&spec, "stories", "id", &reference.stories);
    if let Some(missing) = reference
        .stories
        .iter()
        .find(|id| !stories.iter().any(|story| story["id"] == id.as_str()))
    {
        bail!("C0: story {missing} is not in {}", path.display());
    }
    let known: BTreeSet<&str> = array_or_empty(&spec["requirements"])
        .iter()
        .chain(array_or_empty(&spec["success_criteria"]))
        .map(|item| string_or_empty(&item["id"]))
        .collect();
    let selected: Vec<&str> = chosen(&spec, "requirements", "story", &reference.stories)
        .into_iter()
        .map(|item| string_or_empty(&item["id"]))
        .collect();
    let mut covered = BTreeSet::new();
    let mut outside = BTreeSet::new();
    let mut unreferenced = Vec::new();
    for task in &plan.tasks {
        for criterion in task.criteria() {
            if criterion.refs.is_empty() {
                unreferenced.push(format!("{}/{}", task.id, criterion.id));
            }
            for id in criterion.refs {
                if !known.contains(id.as_str()) {
                    bail!(
                        "C1: {}/{} refers to {id}, which is not in {}",
                        task.id,
                        criterion.id,
                        path.display()
                    );
                }
                if id.starts_with("FR-") && !selected.contains(&id.as_str()) {
                    outside.insert(id.clone());
                }
                covered.insert(id);
            }
        }
    }
    let missing: Vec<&str> = selected
        .iter()
        .copied()
        .filter(|id| !covered.contains(*id))
        .collect();
    if !missing.is_empty() {
        bail!(
            "C2: no acceptance criterion checks {}; give each a criterion whose refs name it",
            missing.join(", ")
        );
    }
    let mut warnings = Vec::new();
    if !outside.is_empty() {
        warnings.push(format!(
            "C3: acceptance criteria refer to requirements outside stories {}: {}",
            reference.stories.join(", "),
            outside.into_iter().collect::<Vec<_>>().join(", ")
        ));
    }
    if !unreferenced.is_empty() {
        warnings.push(format!(
            "C4: acceptance criteria without spec refs: {}",
            unreferenced.join(", ")
        ));
    }
    Ok(Some((spec, warnings)))
}

/// Keeps the run's copy of the spec in step with its plan, so reviewers read
/// the version the plan was checked against even if the file changes later.
pub fn keep_with_run(store: &Store, run: &str, plan: &Plan, spec: Option<&Value>) -> Result<()> {
    match (&plan.spec, spec) {
        (Some(reference), Some(body)) => store.0.execute(
            "INSERT OR REPLACE INTO run_specs (run_id,path,digest,stories,body) VALUES (?,?,?,?,?)",
            rusqlite::params![
                run,
                reference.path,
                reference.digest,
                json!(reference.stories).to_string(),
                body.to_string()
            ],
        )?,
        _ => store
            .0
            .execute("DELETE FROM run_specs WHERE run_id=?", [run])?,
    };
    Ok(())
}

/// The spec items an assignment for `task` checks: the requirements its
/// acceptance criteria refer to (every requirement of the run's stories for
/// a task without refs, such as the whole-branch review), all success
/// criteria, and what is out of scope.
pub fn assignment_view(store: &Store, run: &str, task: &Task) -> Result<Option<Value>> {
    let Some(row) = store.one(
        "SELECT stories, body FROM run_specs WHERE run_id=?",
        &[&run],
    )?
    else {
        return Ok(None);
    };
    let stories: Vec<String> = serde_json::from_str(string_or_empty(&row["stories"]))?;
    let spec: Value = serde_json::from_str(string_or_empty(&row["body"]))?;
    let refs: BTreeSet<String> = task
        .criteria()
        .into_iter()
        .flat_map(|criterion| criterion.refs)
        .collect();
    let requirements: Vec<&Value> = if refs.is_empty() {
        chosen(&spec, "requirements", "story", &stories)
    } else {
        array_or_empty(&spec["requirements"])
            .iter()
            .filter(|item| refs.contains(string_or_empty(&item["id"])))
            .collect()
    };
    Ok(Some(json!({
        "requirements": requirements, "success_criteria": spec["success_criteria"],
        "out_of_scope": spec["out_of_scope"],
    })))
}