agengo 0.3.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
use crate::{
    contract::{array_or_empty, string_or_empty},
    engine::rows,
    store::{code, line, parse, request_kind, respond_hint, show, Store, NOTICES},
};
use anyhow::{Context, Result};
use rusqlite::params;
use serde::Serialize;
use serde_json::{json, Value};
use std::{
    collections::{BTreeMap, BTreeSet},
    io::{self, Write},
};

pub fn waiting_dependents<'a>(
    plan: &'a Value,
    tasks: &BTreeMap<String, Value>,
    task: &str,
) -> Vec<&'a str> {
    let work = array_or_empty(&plan["tasks"]);
    let mut affected = BTreeSet::from([task]);
    loop {
        let previous = affected.len();
        for item in work {
            if array_or_empty(&item["depends"])
                .iter()
                .any(|dep| affected.contains(string_or_empty(dep)))
            {
                affected.insert(string_or_empty(&item["id"]));
            }
        }
        if previous == affected.len() {
            break;
        }
    }
    work.iter()
        .map(|item| string_or_empty(&item["id"]))
        .filter(|id| {
            *id != task
                && affected.contains(id)
                && tasks
                    .get(*id)
                    .is_some_and(|row| row["state"] != "integrated")
        })
        .collect()
}

#[derive(Serialize)]
struct Entry {
    code: String,
    task_id: Option<String>,
    title: String,
    kind: String,
    state: String,
    revision: Option<i64>,
    question: String,
    recommendation: Option<String>,
    reason: Option<String>,
    alternatives: Vec<Value>,
    respond_by: String,
    blocking_tasks: Vec<String>,
    command: Option<String>,
}

impl Entry {
    fn new(row: &Value, plan: &Value, tasks: &BTreeMap<String, Value>) -> Result<Self> {
        let detail = parse(&row["detail"])?;
        let checkpoint = parse(&row["checkpoint"])?;
        let task_id = row["task_id"].as_str();
        let blocking_tasks = task_id.map_or(Vec::new(), |id| waiting_dependents(plan, tasks, id));
        let mut respond_by = match string_or_empty(&checkpoint["phase"]) {
            "plan" => "Before dispatch",
            "final" => "Before final checks run again",
            "integration" => "Before the next integration attempt",
            "build_verify" => "Before the handoff is verified again",
            "review" => "Before the next review",
            "build" => "Before the next build",
            _ => "Before the pending step continues",
        }
        .to_owned();
        if !blocking_tasks.is_empty() {
            respond_by.push_str(&format!(" (blocking {})", blocking_tasks.join(", ")));
        }
        let recommendation = detail["recommendation"]
            .as_str()
            .or(detail["response"].as_str());
        let reason = detail["reason"].as_str().map(str::to_owned).or_else(|| {
            recommendation.map(|_| {
                if row["kind"] == "information" {
                    "The attempt needs this information to continue.".into()
                } else {
                    "The next step needs your response.".into()
                }
            })
        });
        Ok(Self {
            code: code(row).context("missing request code")?,
            task_id: task_id.map(str::to_owned),
            title: string_or_empty(&row["title"]).into(),
            kind: string_or_empty(&row["kind"]).into(),
            state: string_or_empty(&row["state"]).into(),
            revision: row["revision"].as_i64(),
            question: detail["situation"]
                .as_str()
                .unwrap_or(string_or_empty(&row["title"]))
                .into(),
            recommendation: recommendation.map(str::to_owned),
            reason,
            alternatives: array_or_empty(&detail["options"])
                .iter()
                .filter(|option| option["id"] != detail["recommended_choice"])
                .cloned()
                .collect(),
            respond_by,
            blocking_tasks: blocking_tasks.into_iter().map(str::to_owned).collect(),
            command: respond_hint(row).filter(|_| row["state"] == "open"),
        })
    }

    fn immediate(&self) -> bool {
        self.task_id.is_none() || !self.blocking_tasks.is_empty()
    }

    fn print(&self, run: &str) {
        let subject = self.task_id.as_deref().unwrap_or(run);
        print!("- {} · {subject} — {}", self.code, line(&self.question));
        if self.state == "received" {
            println!(" · Response received; waiting to apply or re-check");
            return;
        }
        if let Some(recommendation) = &self.recommendation {
            print!(" · Recommended: {}", line(recommendation));
        }
        if let Some(reason) = &self.reason {
            print!(" · Why: {}", line(reason));
        }
        for option in &self.alternatives {
            print!(
                " · {} — {}",
                string_or_empty(&option["id"]),
                line(string_or_empty(&option["label"]))
            );
        }
        println!(" · {}", self.respond_by);
        if let Some(command) = &self.command {
            println!("  Command: {command}");
        }
    }
}

pub fn view(store: &Store, run: &str, machine: bool) -> Result<()> {
    let plan = store.plan(&store.run(run)?)?;
    let tasks = rows(store, run)?;
    let mut immediate = Vec::new();
    let mut milestone = Vec::new();
    let mut received = Vec::new();
    for request in store.rows(
        &format!("{NOTICES} AND n.state IN ('open','received') ORDER BY n.id"),
        &[&run],
    )? {
        if !request_kind(&request) {
            continue;
        }
        let entry = Entry::new(&request, &plan, &tasks)?;
        if entry.state == "received" {
            received.push(entry);
        } else if entry.immediate() {
            immediate.push(entry);
        } else {
            milestone.push(entry);
        }
    }
    if machine {
        println!(
            "{}",
            serde_json::to_string_pretty(
                &json!({"run_id":run,"immediate":immediate,"at_milestone":milestone,"received":received})
            )?
        );
    } else if immediate.is_empty() && milestone.is_empty() && received.is_empty() {
        println!("[INBOX] {run} · No pending requests.");
    } else {
        for (heading, entries) in [
            ("Needs attention now", immediate),
            ("Can wait for a milestone", milestone),
            ("Response received", received),
        ] {
            if entries.is_empty() {
                continue;
            }
            println!("[INBOX] {run} · {heading}");
            for entry in entries {
                entry.print(run);
            }
        }
    }
    Ok(())
}

pub fn publish(store: &Store, run: &str, plan: &Value, milestone: bool) -> Result<()> {
    let requests = store.rows(
        &format!(
            "{NOTICES} AND n.state='open'
        AND NOT EXISTS(SELECT 1 FROM request_presentations p WHERE p.notice_id=n.id) ORDER BY n.id"
        ),
        &[&run],
    )?;
    if requests.is_empty() {
        return Ok(());
    }
    let tasks = rows(store, run)?;
    let mut deferred = Vec::new();
    for request in requests.into_iter().filter(request_kind) {
        let entry = Entry::new(&request, plan, &tasks)?;
        if entry.immediate() {
            show(&request)?;
            println!("- Respond by — {}", entry.respond_by);
            mark_presented(store, &request)?;
        } else if milestone {
            deferred.push((request, entry));
        }
    }
    if !deferred.is_empty() {
        println!("[INBOX] {run} · New requests at this milestone");
        for (request, entry) in deferred {
            entry.print(run);
            mark_presented(store, &request)?;
        }
    }
    Ok(())
}

fn mark_presented(store: &Store, request: &Value) -> Result<()> {
    io::stdout().flush()?;
    store.0.execute(
        "INSERT OR IGNORE INTO request_presentations (notice_id)
        SELECT id FROM notices WHERE id=? AND state='open'",
        params![request["id"].as_i64()],
    )?;
    Ok(())
}