agengo 0.5.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
use crate::failure::DuplicatesFound;
use crate::{
    agent::Blocker,
    contract::{array_or_empty, string_or_empty},
    plan::{DuplicateMode, Task},
    process::INTERRUPTED,
    store::{parse, show},
};
use anyhow::{bail, Result};
use rusqlite::params;
use serde_json::{json, Value};
use std::sync::atomic::Ordering;

use super::{action_blocker, cleanup, holds, id, Engine};

impl<'a> Engine<'a> {
    pub(super) fn integrate(&self, task: &Task, row: &Value) -> Result<()> {
        let task_id = task.id.as_str();
        if holds(self.store, self.id)?.contains(task_id) {
            return Ok(());
        }
        let previous = self.tip()?;
        let action = self.action(Some(task_id), "integration")?;
        if self.repo.checked_out(&self.reference)? {
            bail!("switch away from {} before integrating", self.reference);
        }
        let path = self.workspace("integration", &id());
        self.repo.worktree(&path, &previous, None)?;
        let candidate = (|| -> Result<String> {
            self.repo.git_at(
                &[
                    "merge",
                    "--no-ff",
                    "-m",
                    &format!("Integrate {}/{task_id}", self.id),
                    string_or_empty(&row["head"]),
                ],
                &path,
            )?;
            let candidate = self.repo.sha_at("HEAD", &path)?;
            self.checks(
                self.plan.setup.iter().chain(&task.setup),
                &path,
                "integration_setup",
                Some(task_id),
            )?;
            self.checks(
                task.verify.iter().chain(&self.plan.integration_verify),
                &path,
                "integration",
                Some(task_id),
            )?;
            // In blocking mode, catch duplicates at the task that adds them,
            // so its Builder fixes them instead of failing the final gate.
            let policy = self.plan.quality();
            if policy.python_duplicates == DuplicateMode::Block {
                crate::quality::duplicate_audit(
                    self,
                    &previous,
                    &candidate,
                    &policy.ignore_paths,
                    Some(task_id),
                    "integration_duplicates",
                    true,
                )?;
            }
            self.repo.snapshot(&path, &candidate)?;
            Ok(candidate)
        })();
        self.discard(&path);
        let candidate = match candidate {
            Ok(candidate) => candidate,
            Err(error) => {
                if INTERRUPTED.load(Ordering::Relaxed) {
                    return Err(error);
                }
                let blocker = action_blocker(&error);
                let prerequisite = blocker.is_some();
                let failures =
                    row["gate_failures"].as_i64().unwrap_or(0) + i64::from(!prerequisite);
                let blocked = prerequisite || failures >= self.settings.gate_limit;
                let message = format!("integration failed against {previous}: {error}");
                let notice = self.store.atomic(|| {
                    self.store.0.execute("UPDATE tasks SET state=?,gate_failures=?,message=?,retry_state=? WHERE run_id=? AND id=?",
                        params![if blocked {"blocked"} else {"pending"},failures,message,
                            blocked.then_some(if prerequisite {"passed"} else {"pending"}),self.id,task_id])?;
                    if blocked {
                        let blocker = blocker.unwrap_or_else(|| Blocker::decision("Give the Builder one more attempt to fix the integration failure."));
                        return Ok(Some(self.request(Some(task),if prerequisite {"integration"} else {"build"},
                            if prerequisite {&row["head"]} else {&Value::Null},&message,Some(&blocker))?));
                    }
                    if let Some(action) = &action {
                        self.store.transition(action,"superseded",None,Some("The check conditions changed."))?;
                    }
                    self.notice(Some(task),"event",json!({"situation":format!("The Builder will fix the integration failure. {message}")}),None)?;
                    Ok(None)
                })?;
                if let Some(notice) = notice {
                    self.notify(&notice)?;
                }
                return Ok(());
            }
        };
        self.store.0.execute(
            "INSERT INTO integrations VALUES (?,?,?,?)",
            params![self.id, task_id, previous, candidate],
        )?;
        self.reconcile()
    }

    pub(super) fn report_progress(&self, situation: String) -> Result<()> {
        let last = self.store.one(
            "SELECT detail FROM notices WHERE run_id=? AND kind='progress' ORDER BY id DESC LIMIT 1",
            &[&self.id],
        )?;
        if let Some(last) = last {
            let detail = parse(&last["detail"])?;
            if detail["progress_key"]
                .as_str()
                .or(detail["situation"].as_str())
                == Some(&situation)
            {
                return Ok(());
            }
        }
        let notice = self.notice(
            None,
            "progress",
            json!({"situation":self.report_retries(situation.clone())?,"progress_key":situation}),
            None,
        )?;
        show(&notice)
    }

    pub(super) fn report_retries(&self, mut situation: String) -> Result<String> {
        let retries: i64 = self.store.0.query_row(
            "SELECT COUNT(*) FROM notices WHERE run_id=?1 AND kind='event' AND id >
                (SELECT COALESCE(MAX(id),0) FROM notices WHERE run_id=?1 AND kind='progress')",
            params![self.id],
            |row| row.get(0),
        )?;
        if retries > 0 {
            situation.push_str(&format!(
                " {retries} rework round(s) recorded after review or integration checks."
            ));
        }
        Ok(situation)
    }

    pub(super) fn delivery(&self, commit: &str) -> Result<Value> {
        let tasks: Vec<_> = self
            .plan
            .tasks
            .iter()
            .map(|task| task.id.as_str())
            .collect();
        let quality = self.store.one("SELECT request FROM attempts WHERE run_id=? AND role='quality_review' AND state='ok' ORDER BY rowid DESC LIMIT 1",
            &[&self.id])?.map(|row| parse(&row["request"])).transpose()?.unwrap_or(Value::Null);
        let quality_note =
            if quality["head"] == commit && quality["plan_revision"] == self.settings.revision {
                " Whole-branch review passed."
            } else {
                ""
            };
        let audit = self.store.one("SELECT request,result,state FROM attempts WHERE run_id=? AND role='quality_duplicates' ORDER BY rowid DESC LIMIT 1",
            &[&self.id])?;
        let duplicate_note = match audit {
            Some(row) if row["state"] == "warning" && parse(&row["request"])?["head"] == commit => {
                let result = parse(&row["result"])?;
                let groups = array_or_empty(&result["duplicates"]).len();
                if groups > 0 {
                    format!(" Warning: {groups} group(s) of duplicated Python functions (see status --json, role quality_duplicates).")
                } else {
                    format!(
                        " Warning: the Python duplicate check could not run ({}).",
                        string_or_empty(&result["error"])
                    )
                }
            }
            _ => String::new(),
        };
        let situation = self.report_retries(format!(
            "Integrated {}/{} tasks ({}). Branch af/{}, commit {commit}. Final checks passed ({}).{quality_note}{duplicate_note}",
            tasks.len(), tasks.len(), tasks.join(", "), self.id, crate::contract::count(self.plan.final_verify.iter().len(), "command"),
        ))?;
        Ok(
            json!({"situation":situation,"response":"Review the result and decide whether to merge."}),
        )
    }

    pub(super) fn final_steps(&self) -> Result<bool> {
        let commit = self.tip()?;
        let action = self.action(None, "final")?;
        let path = self.workspace("final", &id());
        self.repo.worktree(&path, &commit, None)?;
        let verified = (|| -> Result<()> {
            self.checks(self.plan.setup.iter(), &path, "final_setup", None)?;
            self.checks(self.plan.final_verify.iter(), &path, "final", None)?;
            crate::quality::verify(self, &path, &commit)?;
            self.repo.snapshot(&path, &commit)?;
            if self.repo.current(&self.reference)?.as_deref() != Some(&commit) {
                bail!("final verification no longer matches the delivery commit");
            }
            Ok(())
        })();
        self.discard(&path);
        if let Err(error) = verified {
            if INTERRUPTED.load(Ordering::Relaxed) {
                return Err(error);
            }
            let notice = self.store.atomic(|| {
                self.store.0.execute("UPDATE runs SET state='final_failed',message=? WHERE id=?",params![error.to_string(),self.id])?;
                if let Some(blocker) = action_blocker(&error) {
                    self.request(None,"final",&json!(commit),&error.to_string(),Some(&blocker))
                } else {
                    let blocker = if error.is::<DuplicatesFound>() {
                        Blocker::decision("Approve a revised plan: add a task that merges the duplicates, add ignore_paths, or set quality.python_duplicates: warn.")
                            .recommend_b()
                            .alternative("Re-run the final checks without changing the plan.")
                            .reason("The Python duplicate gate blocks delivery; a re-run gives the same result.")
                    } else {
                        Blocker::decision("Re-run the final checks after fixing the environment or tools.")
                            .alternative("Approve a revised plan, for example with a fix-up task or changed final_verify, setup or quality settings.")
                            .reason("Integrated tasks are kept; only the final checks failed.")
                    };
                    self.request(None,"final",&json!(commit),&format!("Final checks failed on {commit}. {error}"),Some(&blocker))
                }
            })?;
            self.notify(&notice)?;
            return Ok(false);
        }
        let (applied, notice) = self.store.atomic(|| {
            self.store.0.execute(
                "UPDATE runs SET state='done',message=NULL WHERE id=?",
                params![self.id],
            )?;
            let applied = action
                .as_ref()
                .map(|action| {
                    self.acknowledge(
                        action,
                        None,
                        &format!("Final checks unblocked on {commit}."),
                    )
                })
                .transpose()?;
            Ok((
                applied,
                self.notice(None, "delivery", self.delivery(&commit)?, None)?,
            ))
        })?;
        if let Some(applied) = applied {
            show(&applied)?;
        }
        show(&notice)?;
        match cleanup(self.repo, self.id, true) {
            Ok(summary) => println!("- Cleanup — {summary}"),
            Err(error) => eprintln!("agengo: cleanup after delivery failed: {error:#}"),
        }
        Ok(true)
    }
}