mod complete;
mod dispatch;
mod integrate;
use crate::failure::DependencyMissing;
use crate::process::CANCEL_ASSIGNMENTS;
use crate::{
adapter::Action,
agent::{Assignment, Blocker, BlockerKind, Choice, Handoff, Role},
context,
contract::{overlaps, string_or_empty},
handoff, inbox,
integrity::Baseline,
plan::{Argv, Plan, Task},
process::{run, Repo, INTERRUPTED},
store::{code, parse, request_kind, show, Settings, Store, HANDOFFS},
};
use anyhow::{bail, Context, Result};
use dispatch::run_assignment;
use rusqlite::params;
use serde_json::{json, Value};
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::{atomic::Ordering, mpsc, OnceLock},
thread,
time::Instant,
};
use uuid::Uuid;
struct CancelAssignments;
struct AssignmentOutput {
response: Value,
setup_artifacts: BTreeSet<String>,
verification: Option<Value>,
}
impl Drop for CancelAssignments {
fn drop(&mut self) {
CANCEL_ASSIGNMENTS.store(true, Ordering::Relaxed);
}
}
pub fn id() -> String {
Uuid::new_v4().simple().to_string()
}
pub fn reference(id: &str) -> String {
format!("refs/heads/af/{id}")
}
pub fn rows(store: &Store, id: &str) -> Result<BTreeMap<String, Value>> {
Ok(store
.rows("SELECT * FROM tasks WHERE run_id=?", &[&id])?
.into_iter()
.map(|value| (string_or_empty(&value["id"]).to_owned(), value))
.collect())
}
pub fn cleanup(repo: &Repo, id: &str, refs: bool) -> Result<String> {
let mut worktrees = 0;
for root in repo.run_worktree_roots(id) {
worktrees += repo.remove_worktrees_under(&root)?;
}
let deleted = if refs {
repo.delete_refs(&[
&format!("refs/heads/af-work/{id}/"),
&format!("{}/{id}/", handoff::BUILD_REFS),
])?
.len()
} else {
0
};
Ok(format!(
"Removed {worktrees} worktree(s) and {deleted} temporary ref(s) of run {id}."
))
}
pub fn holds(store: &Store, id: &str) -> Result<BTreeSet<String>> {
Ok(store
.rows("SELECT task_id FROM task_holds WHERE run_id=?", &[&id])?
.iter()
.map(|value| string_or_empty(&value["task_id"]).to_owned())
.collect())
}
pub fn progress(plan: &Plan, rows: &BTreeMap<String, Value>, held: &BTreeSet<String>) -> String {
let integrated = rows
.values()
.filter(|row| row["state"] == "integrated")
.count();
let mut result = format!("Integrated {integrated}/{} tasks.", rows.len());
let mut active = Vec::new();
let mut blocked = Vec::new();
let mut waiting = Vec::new();
let mut ready = Vec::new();
for task in &plan.tasks {
let key = task.id.as_str();
if held.contains(key) {
continue;
}
match string_or_empty(&rows[key]["state"]) {
"building" | "verifying" | "ready_review" | "reviewing" | "passed" => active.push(key),
"blocked" => blocked.push(key),
"pending"
if task
.depends
.iter()
.any(|dep| rows[dep.as_str()]["state"] != "integrated") =>
{
waiting.push(key)
}
"pending" => ready.push(key),
_ => {}
}
}
for (label, ids) in [
("Active", active),
("Blocked", blocked),
("Waiting on dependencies", waiting),
("Ready", ready),
("Paused", held.iter().map(String::as_str).collect()),
] {
if !ids.is_empty() {
result.push_str(&format!(" {label}: {}.", ids.join(", ")));
}
}
result
}
fn incident_blocker(role: Role) -> Blocker {
Blocker::decision(format!("Retry the {} attempt; add guidance with --note if needed.", role.as_str()))
.alternative("Approve a revised plan if the problem comes from the scope, the checks or the environment.")
.reason("The previous attempt failed for a technical reason (agent error, timeout or a reply that breaks the contract). See status --json for details.")
}
pub fn action_blocker(error: &anyhow::Error) -> Option<Blocker> {
error
.downcast_ref::<Action>()
.map(|action| Blocker::action(&action.recommendation, &action.reason))
}
pub struct Engine<'a> {
pub repo: &'a Repo,
pub store: &'a Store,
pub run: Value,
pub settings: Settings,
pub plan: Plan,
pub profile: Value,
pub id: &'a str,
mode: Handoff,
reference: String,
integrity: OnceLock<Baseline>,
}
impl<'a> Engine<'a> {
pub fn new(repo: &'a Repo, store: &'a Store, id: &'a str) -> Result<Self> {
let run = store.run(id)?;
let plan = store.plan(&run)?;
let saved = store.one("SELECT body FROM run_role_profiles WHERE run_id=?", &[&id])?;
let mut profile = match saved {
Some(row) => parse(&row["body"])?,
None => crate::contract::profile(None)?,
};
if profile["roles"]["verify"].is_null() {
profile["roles"]["verify"] = crate::contract::profile(None)?["roles"]["verify"].take();
}
let mut settings = Settings::from_row(&run)?;
settings.config = crate::config::load(&repo.root)?;
Ok(Self {
repo,
store,
settings,
run,
plan,
profile,
id,
mode: if store.handoff_mode(id)? == "commit" {
Handoff::Commit
} else {
Handoff::Worktree
},
reference: reference(id),
integrity: OnceLock::new(),
})
}
pub fn discard(&self, path: &Path) {
if let Err(error) = self.repo.remove_worktree(path) {
eprintln!(
"agengo: could not remove worktree {}: {error:#}",
path.display()
);
}
}
pub fn tip(&self) -> Result<String> {
Ok(string_or_empty(&self.store.run(self.id)?["tip"]).into())
}
pub fn workspace(&self, phase: &str, key: &str) -> PathBuf {
self.repo.worktrees.join(self.id).join(phase).join(key)
}
pub fn timeout(&self) -> u64 {
self.settings.timeout
}
fn guard(&self) -> Result<()> {
match self.integrity.get() {
Some(baseline) => baseline.check(self.repo),
None => Ok(()),
}
}
fn notice(
&self,
task: Option<&Task>,
kind: &str,
detail: Value,
checkpoint: Option<Value>,
) -> Result<Value> {
self.store.notice(
self.id,
task.map(|task| task.id.as_str()),
kind,
task.map_or(self.plan.goal.as_str(), Task::title),
detail,
checkpoint,
)
}
fn action(&self, task: Option<&str>, phase: &str) -> Result<Option<Value>> {
let possible = self.store.pending(self.id, task)?;
if let Some(row) = possible {
if row["kind"] == "action"
&& row["state"] == "received"
&& parse(&row["checkpoint"])?["phase"] == phase
{
return Ok(Some(row));
}
}
Ok(None)
}
fn acknowledge(&self, request: &Value, task: Option<&Task>, outcome: &str) -> Result<Value> {
self.store
.transition(request, "resolved", None, Some(outcome))?;
self.notice(
task,
"control",
json!({"situation":format!("{} · {outcome}",code(request).unwrap_or_default())}),
None,
)
}
fn request(
&self,
task: Option<&Task>,
phase: &str,
head: &Value,
message: &str,
blocker: Option<&Blocker>,
) -> Result<Value> {
let mut detail = json!({"situation":message});
fn filled(value: &Option<String>) -> Option<&str> {
value.as_deref().filter(|value| !value.trim().is_empty())
}
let recommendation = blocker.and_then(|blocker| filled(&blocker.recommendation));
let reason = blocker.and_then(|blocker| filled(&blocker.reason));
let kind = match blocker.map(|blocker| blocker.kind) {
Some(BlockerKind::Action) => {
detail["recommendation"] =
json!(recommendation.unwrap_or("Resolve the condition that blocks the run."));
detail["reason"] = json!(
reason.unwrap_or("The task needs this condition before it can run again.")
);
detail["response"] =
json!("Confirm when it is done and briefly note what changed.");
"action"
}
Some(BlockerKind::Decision) => {
let choice = match blocker.and_then(|blocker| blocker.recommended_choice) {
Some(Choice::B) => "B",
_ => "A",
};
let alternative = blocker.and_then(|blocker| filled(&blocker.alternative));
let a = if choice == "A" {
recommendation
} else {
alternative
}
.unwrap_or("Retry with your guidance under the current plan.");
let b = if choice == "B" {
recommendation
} else {
alternative
}
.unwrap_or("Approve a revised plan.");
detail["recommendation"] =
json!(format!("{choice} · {}", if choice == "A" { a } else { b }));
detail["recommended_choice"] = json!(choice);
detail["reason"] = json!(reason.unwrap_or(if choice == "A" {
"Keeps the approved commitments and gives the agent guidance."
} else {
"Changing commitments must be recorded in the plan."
}));
detail["options"] = json!([{"id":"A","label":a},{"id":"B","label":b}]);
detail["response"] = json!("Choose A with guidance, or B with a new plan.");
"decision"
}
_ => {
detail["response"] = json!(recommendation.unwrap_or(
"Provide the information or constraint the task needs to continue."
));
"information"
}
};
let task_id = task.map(|task| task.id.as_str());
detail["impact"] = json!(if let Some(id) = task_id {
self.impact(id)?
} else {
"Integrated tasks are kept. The run is waiting for final checks.".into()
});
let checkpoint = json!({"phase":phase,"head":head});
if let Some(previous) = self.store.pending(self.id, task_id)? {
if kind == "action"
&& previous["kind"] == "action"
&& parse(&previous["checkpoint"])? == checkpoint
&& parse(&previous["detail"])?["situation"] == message
{
self.store.transition(
&previous,
"open",
None,
Some("The condition is still not met."),
)?;
self.store.0.execute(
"UPDATE notices SET detail=? WHERE id=?",
params![detail.to_string(), previous["id"].as_i64()],
)?;
return self
.store
.pending(self.id, task_id)?
.context("missing reopened request");
}
self.store.transition(
&previous,
"superseded",
None,
Some("The run raised a newer request."),
)?;
}
self.notice(task, kind, detail, Some(checkpoint))
}
fn notify(&self, notice: &Value) -> Result<()> {
if request_kind(notice) {
inbox::publish(self.store, self.id, &self.plan, false)
} else {
show(notice)
}
}
fn impact(&self, task: &str) -> Result<String> {
let tasks = rows(self.store, self.id)?;
let waits = inbox::waiting_dependents(&self.plan, &tasks, task);
let consequence = if waits.is_empty() {
String::new()
} else {
format!(". Waiting dependents: {}", waits.join(", "))
};
Ok(format!(
"{task} is on hold{consequence}. Independent tasks continue."
))
}
fn reconcile(&self) -> Result<()> {
let current = self.repo.current(&self.reference)?;
if let Some(intent) = self
.store
.one("SELECT * FROM integrations WHERE run_id=?", &[&self.id])?
{
let previous = string_or_empty(&intent["previous"]);
let candidate = string_or_empty(&intent["candidate"]);
let task = string_or_empty(&intent["task_id"]);
if current.as_deref() == Some(previous) && previous != candidate {
if self.repo.checked_out(&self.reference)? {
bail!(
"switch away from {} before resuming the run",
self.reference
);
}
self.repo
.set_ref(&self.reference, candidate, Some(previous))?;
} else if current.as_deref() != Some(candidate) {
bail!(
"{} changed outside agengo during integration",
self.reference
);
}
let applied = self.store.atomic(|| {
self.store.0.execute(
"UPDATE runs SET tip=? WHERE id=?",
params![candidate, self.id],
)?;
self.store.0.execute(
"UPDATE tasks SET state='integrated',message=NULL WHERE run_id=? AND id=?",
params![self.id, task],
)?;
self.store.0.execute(
"INSERT OR REPLACE INTO integrated_tasks VALUES (?,?,?)",
params![self.id, task, candidate],
)?;
self.store
.0
.execute("DELETE FROM integrations WHERE run_id=?", params![self.id])?;
self.action(Some(task), "integration")?
.map(|action| {
self.acknowledge(
&action,
Some(self.plan.task(task)?),
&format!("Unblocked {task}. Integration checks passed."),
)
})
.transpose()
})?;
if let Some(applied) = applied {
show(&applied)?;
}
return Ok(());
}
let base = string_or_empty(&self.run["base"]);
let current = if self.store.run(self.id)?["ref_initialized"] == 0 {
if current.is_none() {
self.repo.set_ref(&self.reference, base, None)?;
}
let current = current.unwrap_or_else(|| base.into());
if current == base {
self.store.0.execute(
"UPDATE runs SET ref_initialized=1 WHERE id=?",
params![self.id],
)?;
}
Some(current)
} else {
current
};
if current.as_deref() != Some(self.tip()?.as_str()) {
bail!(
"{} differs from the recorded integration commit {tip}; restore it with `git update-ref {} {tip}` before resuming",
self.reference,
self.reference,
tip = self.tip()?
);
}
Ok(())
}
pub fn attempt(
&self,
attempt: &str,
task: Option<&str>,
role: &str,
request: &Value,
) -> Result<()> {
self.store.0.execute(
"INSERT INTO attempts VALUES (?,?,?,?,'active',?,NULL)",
params![attempt, self.id, task, role, request.to_string()],
)?;
Ok(())
}
pub fn result(&self, attempt: &str, state: &str, report: &Value) -> Result<()> {
self.store.0.execute(
"UPDATE attempts SET state=?,result=? WHERE id=?",
params![state, report.to_string(), attempt],
)?;
Ok(())
}
pub fn checks<'b>(
&self,
commands: impl IntoIterator<Item = &'b Argv>,
path: &Path,
role: &str,
task: Option<&str>,
) -> Result<()> {
for command in commands {
let key = id();
let head = self.repo.sha_at("HEAD", path)?;
self.attempt(
&key,
task,
role,
&json!({"command":command,"worktree":path,"head":head}),
)?;
let started = Instant::now();
let phase = if role.ends_with("_setup") {
crate::sandbox::Phase::Setup
} else {
crate::sandbox::Phase::Check
};
let result = run(
&mut crate::sandbox::plan_command(command, path, &self.settings.config, phase)?,
None,
Some(self.timeout()),
);
let report = match &result {
Ok(output) => match self.repo.snapshot(path, &head) {
Ok(()) => {
json!({"exit":output.status.code().unwrap_or(-1),"stdout":String::from_utf8_lossy(&output.stdout),
"stderr":String::from_utf8_lossy(&output.stderr)})
}
Err(error) => json!({"exit":null,"stderr":error.to_string()}),
},
Err(error) => json!({"exit":null,"stderr":format!("{error:#}")}),
};
let elapsed = started.elapsed();
let success = report["exit"] == 0;
self.store.atomic(|| {
self.store.record_duration(&key, elapsed)?;
self.result(&key, if success { "ok" } else { "failed" }, &report)
})?;
self.guard()?;
if !success {
let message = format!(
"check failed ({})\n{}",
json!(command),
context::last_chars(context::failure_text(&report), 1500)
);
if let Err(error) = result {
if error.downcast_ref::<std::io::Error>().is_some_and(|error| {
matches!(
error.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied
)
}) {
return Err(Action {
message,
recommendation: format!(
"Check that {} is installed and executable.",
command.first().map_or("", String::as_str)
),
reason: "The check command could not start.".into(),
}
.into());
}
}
bail!("{message}");
}
}
Ok(())
}
pub fn execute(&self) -> Result<bool> {
if matches!(
string_or_empty(&self.run["state"]),
"awaiting_approval" | "approval_rejected"
) {
inbox::publish(self.store, self.id, &self.plan, false)?;
return Ok(false);
}
self.reconcile()?;
if self.run["state"] == "done" {
show(
&json!({"kind":"delivery","run_id":self.id,"title":self.plan.goal,"detail":self.delivery(&self.tip()?)?.to_string()}),
)?;
return Ok(true);
}
if self.run["state"] == "final_failed" {
let blocked = self.store.atomic(|| {
if let Some(pending) = self.store.pending(self.id, None)? {
if pending["kind"] == "action" && pending["state"] == "open" {
return Ok(Some(pending));
}
if pending["kind"] == "decision" {
self.store.transition(
&pending,
"superseded",
None,
Some("Final checks re-run requested."),
)?;
}
}
self.store.0.execute(
"UPDATE runs SET state='running',message=NULL WHERE id=?",
params![self.id],
)?;
Ok(None)
})?;
if blocked.is_some() {
inbox::publish(self.store, self.id, &self.plan, false)?;
return Ok(false);
}
}
self.store.atomic(|| {
self.store.0.execute("UPDATE attempts SET state='interrupted' WHERE run_id=? AND state='active'",params![self.id])?;
self.store.0.execute("UPDATE tasks SET attempt=NULL,state=CASE state WHEN 'building' THEN 'pending' WHEN 'reviewing' THEN 'ready_review' END
WHERE run_id=? AND state IN ('building','reviewing')",params![self.id])?;
Ok(())
})?;
self.store.atomic(|| {
for (task,row) in rows(self.store,self.id)? {
if row["state"] != "blocked" || self.store.one(
"SELECT 1 FROM notices WHERE run_id=? AND task_id=? AND (state IN ('open','received') OR kind='incident')",
&[&self.id,&task])?.is_some() { continue; }
let phase = if row["retry_state"] == "ready_review" {"review"} else {"build"};
self.request(Some(self.plan.task(&task)?),phase,
if phase == "review" {&row["head"]} else {&Value::Null},
row["message"].as_str().unwrap_or("Task blocked."),None)?;
}
Ok(())
})?;
inbox::publish(self.store, self.id, &self.plan, false)?;
if self.integrity.get().is_none() {
let _ = self.integrity.set(Baseline::capture(self.repo)?);
}
let (send, receive) = mpsc::channel();
let result = thread::scope(|scope| -> Result<bool> {
let _cancel_workers = CancelAssignments;
let mut active = BTreeMap::<String, Assignment>::new();
let mut integrated = rows(self.store, self.id)?
.values()
.filter(|row| row["state"] == "integrated")
.count();
loop {
if INTERRUPTED.load(Ordering::Relaxed) {
bail!("run interrupted");
}
for record in self.store.rows(&format!("{HANDOFFS} AND EXISTS(SELECT 1 FROM tasks t WHERE t.run_id=a.run_id
AND t.id=a.task_id AND t.attempt=a.id AND t.state='verifying') ORDER BY a.rowid"),&[&self.id])? {
self.finish_handoff(&record)?;
}
let held = holds(self.store, self.id)?;
for (task_id, row) in rows(self.store, self.id)? {
if row["state"] == "passed" && !held.contains(&task_id) {
self.integrate(self.plan.task(&task_id)?, &row)?;
}
}
let current = rows(self.store, self.id)?;
let now_integrated = current
.values()
.filter(|row| row["state"] == "integrated")
.count();
if now_integrated == current.len() {
return self.final_steps();
}
for (role, state) in [(Role::Review, "ready_review"), (Role::Build, "pending")] {
for task in &self.plan.tasks {
if active.len() >= self.settings.jobs {
break;
}
let task_id = task.id.as_str();
if current[task_id]["state"] != state
|| held.contains(task_id)
|| task
.depends
.iter()
.any(|dep| current[dep.as_str()]["state"] != "integrated")
|| active
.values()
.any(|job| overlaps(&task.owns, &job.task.owns))
{
continue;
}
let request = match self.dispatch(task, ¤t, role) {
Ok(Some(request)) => request,
Ok(None) => continue,
Err(error) if error.is::<DependencyMissing>() => {
let notice = self.store.atomic(|| {
self.store.0.execute("UPDATE tasks SET state='blocked',retry_state=?,message=? WHERE run_id=? AND id=?",
params![state,error.to_string(),self.id,task_id])?;
self.request(Some(task),role.as_str(),if role == Role::Review {¤t[task_id]["head"]} else {&Value::Null},
&error.to_string(),Some(&Blocker::decision("Approve a revised plan whose dependencies match the integrated tasks.")
.recommend_b()
.alternative(format!("Retry after checking branch af/{}.",self.id))
.reason("The task's starting commit lacks an integrated dependency.")))
})?;
self.notify(¬ice)?;
continue;
}
Err(error) => return Err(error),
};
let key = request.attempt_id.clone();
active.insert(key.clone(), request.clone());
let sender = send.clone();
let (repo, settings, plan, profile) =
(self.repo, &self.settings, &self.plan, &self.profile);
scope.spawn(move || {
let started = Instant::now();
let (usage, reply) =
run_assignment(repo, settings, plan, profile, &request);
let _ = sender.send((key, started.elapsed(), usage, reply));
});
}
}
if active.is_empty() || now_integrated > integrated {
let latest = rows(self.store, self.id)?;
self.report_progress(progress(&self.plan, &latest, &held))?;
inbox::publish(self.store, self.id, &self.plan, true)?;
}
if active.is_empty() {
return Ok(false);
}
integrated = now_integrated;
if let Ok((key, elapsed, usage, reply)) =
receive.recv_timeout(std::time::Duration::from_millis(250))
{
self.store.record_duration(&key, elapsed)?;
self.store.record_usage(&key, usage.as_ref())?;
let request = active.remove(&key).context("unknown completed attempt")?;
let reply = self.guard().and(reply);
self.complete(&request, reply)?;
}
}
});
CANCEL_ASSIGNMENTS.store(false, Ordering::Relaxed);
let timings = receive.try_iter().try_for_each(|(key, elapsed, usage, _)| {
self.store.record_duration(&key, elapsed)?;
self.store.record_usage(&key, usage.as_ref())
});
let completed = result?;
timings?;
Ok(completed)
}
}