use crate::failure::VerifyFailed;
use crate::{
adapter::{invoke_measured, Action},
agent::{Assignment, Blocker, Handoff, Role},
context,
contract::string_or_empty,
handoff,
plan::{Plan, Task},
process::{checked, run, Repo, INTERRUPTED},
store::{parse, show, Settings, HANDOFFS},
verification,
};
use anyhow::{bail, Result};
use rusqlite::params;
use serde_json::{json, Value};
use std::{collections::BTreeMap, sync::atomic::Ordering};
use super::{action_blocker, holds, id, AssignmentOutput, Engine};
impl<'a> Engine<'a> {
pub(super) fn dispatch(
&self,
task: &Task,
all: &BTreeMap<String, Value>,
role: Role,
) -> Result<Option<Assignment>> {
let task_id = task.id.as_str();
let row = &all[task_id];
let attempt = id();
let path = self.workspace(role.as_str(), &attempt);
let tip = self.tip()?;
let draft = if role == Role::Build && self.mode == Handoff::Worktree {
let last = self.store.one(
&format!("{HANDOFFS} AND a.task_id=? ORDER BY a.rowid DESC LIMIT 1"),
&[&self.id, &task_id],
)?;
match last {
Some(last)
if last["state"] == "failed"
&& parse(&last["request"])?["plan_revision"] == self.settings.revision =>
{
last["candidate"].as_str().map(str::to_owned)
}
_ => None,
}
} else {
None
};
let start = draft
.as_deref()
.or_else(|| row["head"].as_str())
.unwrap_or(&tip);
let mut request = Assignment::new(
&attempt,
self.settings.revision,
role,
self.id,
&self.plan,
task,
start,
path,
);
request.integration_sha = tip.clone();
request.feedback = row["message"].as_str().map(str::to_owned);
request.base = match role {
Role::Review => row["review_base"].as_str().map(str::to_owned),
Role::Build => Some(tip.clone()),
};
if role == Role::Build {
request.builder_handoff = Some(self.mode);
if self.mode == Handoff::Worktree {
request.branch = Some(format!("agengo-work/{}/{task_id}/{attempt}", self.id));
if !self.repo.ancestor(&tip, start)? {
request.merge_parent = Some(tip.clone());
}
}
}
let applied = self.store.atomic(|| {
if holds(self.store,self.id)?.contains(task_id) { return Ok(None); }
request.relationships = context::relationships(self.repo,self.store,self.id,task,&self.plan,start,all)?;
request.decisions = json!(self.store.rows("SELECT id,note FROM decisions WHERE run_id=? AND (task_id IS NULL OR task_id=?) ORDER BY id",
&[&self.id,&task_id])?);
request.context = context::packet(self.store,self.id,task)?;
if role == Role::Build {
if let Some(failure) = context::last_failure(self.store,self.id,task_id)? {
request.context["last_failure"] = failure;
}
}
let mut applied = None;
if let Some(pending) = self.store.pending(self.id,Some(task_id))?.filter(|row| row["state"] == "received") {
request.human_request_id = pending["id"].as_i64();
if matches!(string_or_empty(&pending["kind"]),"decision"|"information") {
applied = Some(self.acknowledge(&pending,Some(task),&format!("Applied your response to the {} attempt of {task_id}.",role.as_str()))?);
}
}
self.attempt(&attempt,Some(task_id),role.as_str(),&request.to_value())?;
self.store.0.execute("UPDATE tasks SET state=?,attempt=? WHERE run_id=? AND id=?",
params![if role == Role::Build {"building"} else {"reviewing"},attempt,self.id,task_id])?;
Ok(Some(applied))
})?;
let Some(applied) = applied else {
return Ok(None);
};
if let Some(applied) = applied {
show(&applied)?;
}
Ok(Some(request))
}
pub(super) fn verify_candidate(&self, task: &Task, sha: &str) -> Result<()> {
let task_id = task.id.as_str();
let path = self.workspace("build-verification", &id());
let result = (|| -> Result<()> {
self.repo.worktree(&path, sha, None)?;
self.checks(
self.plan.setup.iter().chain(&task.setup),
&path,
"build_verify_setup",
Some(task_id),
)?;
self.checks(task.verify.iter(), &path, "build_verify", Some(task_id))?;
self.repo.snapshot(&path, sha)
})();
self.discard(&path);
result.map_err(|error| {
if error.is::<Action>() || INTERRUPTED.load(Ordering::Relaxed) {
error
} else {
VerifyFailed(format!(
"The build did not pass the task's checks. {error:#}"
))
.into()
}
})
}
pub(super) fn finish_handoff(&self, record: &Value) -> Result<()> {
let task_id = string_or_empty(&record["task_id"]);
if holds(self.store, self.id)?.contains(task_id) {
return Ok(());
}
let request = Assignment::from_value(&parse(&record["request"])?)?;
if request.plan_revision != self.settings.revision {
bail!("handoff belongs to a superseded plan revision");
}
let key = string_or_empty(&record["attempt_id"]);
let task = self.plan.task(task_id)?;
let mut output = parse(&record["result"])?;
let mut candidate = record["candidate"].clone();
let path = self.workspace("build-verification", &id());
let verified = (|| -> Result<()> {
let sha = handoff::pin(self.repo, &request, record)?;
candidate = json!(sha);
if record["state"] == "verified" {
return Ok(());
}
self.store.0.execute(
"UPDATE build_handoffs SET state='pinned',candidate=? WHERE attempt_id=?",
params![sha, key],
)?;
self.repo.worktree(&path, &sha, None)?;
self.checks(
self.plan.setup.iter().chain(&task.setup),
&path,
"build_verify_setup",
Some(task_id),
)?;
self.checks(task.verify.iter(), &path, "build_verify", Some(task_id))?;
self.repo.snapshot(&path, &sha)?;
if self.repo.current(&handoff::reference(&request))?.as_deref() != Some(&sha) {
bail!("handoff candidate ref changed during verification");
}
self.store.0.execute(
"UPDATE build_handoffs SET state='verified' WHERE attempt_id=?",
params![key],
)?;
Ok(())
})();
self.discard(&path);
output["candidate_sha"] = candidate.clone();
if let Err(error) = verified {
if INTERRUPTED.load(Ordering::Relaxed) {
return Err(error);
}
let action = action_blocker(&error);
let waiting = action.is_some();
let message = format!("Could not verify the handoff of {task_id}. {error}");
let blocker = action
.unwrap_or_else(|| Blocker::decision("Ask the Builder to fix the failing checks."));
output["verification_error"] = json!(error.to_string());
let notice = self.store.atomic(|| {
self.store.0.execute("UPDATE build_handoffs SET state=? WHERE attempt_id=?",params![if waiting {"waiting"} else {"failed"},key])?;
self.result(key,if waiting {"handoff"} else {"error"},&output)?;
self.store.0.execute("UPDATE tasks SET state='blocked',message=?,retry_state=?,attempt=? WHERE run_id=? AND id=?",
params![message,if waiting {"verifying"} else {"pending"},waiting.then_some(key),self.id,task_id])?;
self.request(Some(task),if waiting {"build_verify"} else {"build"},if waiting {&candidate} else {&Value::Null},&message,Some(&blocker))
})?;
return self.notify(¬ice);
}
output["verification"] = json!("ok");
let applied = self.store.atomic(|| {
self.store.0.execute("UPDATE build_handoffs SET state='accepted' WHERE attempt_id=?",params![key])?;
self.result(key,"done",&output)?;
self.store.0.execute("UPDATE tasks SET state='ready_review',head=?,review_base=?,message=?,attempt=NULL,retry_state=NULL WHERE run_id=? AND id=?",
params![string_or_empty(&candidate),string_or_empty(&record["review_base"]),string_or_empty(&output["summary"]),self.id,task_id])?;
let action = self.action(Some(task_id),"build_verify")?.or(self.action(Some(task_id),"build")?);
action.map(|action| self.acknowledge(&action,Some(task),&format!("Unblocked {task_id}. Checks passed on {}.",string_or_empty(&candidate)))).transpose()
})?;
if let Some(applied) = applied {
show(&applied)?;
}
Ok(())
}
}
pub(super) fn run_assignment(
repo: &Repo,
settings: &Settings,
plan: &Plan,
profile: &Value,
request: &Assignment,
) -> (Option<Value>, Result<AssignmentOutput>) {
let mut usage = None;
let result = prepare_and_invoke(repo, settings, plan, profile, request, &mut usage);
(usage, result)
}
fn prepare_and_invoke(
repo: &Repo,
settings: &Settings,
plan: &Plan,
profile: &Value,
request: &Assignment,
usage: &mut Option<Value>,
) -> Result<AssignmentOutput> {
let path = request.worktree.as_path();
let start = request.head.as_str();
let task = &request.task;
let timeout = settings.timeout;
let worktree = request.is_worktree_build();
let branch = (request.role == Role::Build).then(|| {
format!(
"agengo-work/{}/{}/{}",
request.run_id, task.id, request.attempt_id
)
});
repo.worktree(path, start, branch.as_deref())?;
for command in plan.setup.iter().chain(&task.setup) {
checked(
run(
&mut crate::sandbox::plan_command(
command,
path,
&settings.config,
crate::sandbox::Phase::Setup,
)?,
None,
Some(timeout),
)?,
"setup failed",
)?;
repo.snapshot(path, start)?;
}
let setup_artifacts = repo.untracked(path, false)?;
let index = if worktree {
handoff::prepare(repo, request, path)?;
Some(repo.git_at(&["ls-files", "--stage", "-z"], path)?)
} else {
None
};
let invocation = invoke_measured(
settings.agent.as_deref(),
settings.auth,
&request.to_value(),
path,
timeout,
profile,
&settings.config,
);
*usage = invocation.usage;
let output = invocation.reply?;
let verification = (request.role == Role::Review && plan.quality().verify_findings)
.then(|| {
verification::verify(
request,
&output,
path,
settings.agent.as_deref(),
settings.auth,
timeout,
profile,
&settings.config,
)
})
.flatten()
.map(|(spent, report)| {
*usage = crate::usage::combine(usage.take(), spent);
report
});
if let Some(index) = index {
if matches!(string_or_empty(&output["status"]), "ready" | "done")
&& repo.git_at(&["ls-files", "--stage", "-z"], path)? != index
{
bail!("builder changed the Git index during worktree handoff");
}
}
Ok(AssignmentOutput {
response: output,
setup_artifacts,
verification,
})
}