use crate::{
context,
contract::{array_or_empty, string_or_empty, text},
engine::{find_task, holds, progress, reference, rows, title},
process::Repo,
store::{code, notice_json, parse, request_kind, show, Store, HANDOFFS, NOTICES},
};
use anyhow::{anyhow, bail, Context, Result};
use rusqlite::params;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
pub fn status(repo: &Repo, store: &Store, id: &str, machine: bool) -> Result<()> {
let mut run = store.run(id)?;
run["builder_handoff"] = json!(store.handoff_mode(id)?);
let plan = store.plan(&run)?;
let tasks = rows(store, id)?;
let notices = store.rows(&format!("{NOTICES} ORDER BY n.id"), &[&id])?;
let held = holds(store, id)?;
let branch = repo.current(&reference(id))?;
if machine {
let notices = notices
.into_iter()
.map(notice_json)
.collect::<Result<Vec<_>>>()?;
let handoffs = store
.rows(&format!("{HANDOFFS} ORDER BY a.rowid"), &[&id])?
.into_iter()
.map(|mut row| {
row["paths"] = parse(&row["paths"])?;
row["parents"] = parse(&row["parents"])?;
let object = row.as_object_mut().unwrap();
object.remove("request");
object.remove("result");
Ok(row)
})
.collect::<Result<Vec<_>>>()?;
let attempts = store
.rows(
"SELECT a.*, t.duration_ms, u.attempt_id AS usage_attempt, u.input_tokens, u.output_tokens,
u.cache_read_tokens, u.cache_write_tokens, u.cost_usd, u.model
FROM attempts a LEFT JOIN attempt_timings t ON t.attempt_id=a.id
LEFT JOIN attempt_usage u ON u.attempt_id=a.id
WHERE a.run_id=? ORDER BY a.rowid",
&[&id],
)?
.into_iter()
.map(|mut row| {
row["request"] = parse(&row["request"])?;
row["result"] = parse(&row["result"])?;
if row["duration_ms"].is_null() {
row.as_object_mut().unwrap().remove("duration_ms");
}
let object = row.as_object_mut().unwrap();
let metered = !object.remove("usage_attempt").unwrap_or(Value::Null).is_null();
let mut usage = serde_json::Map::new();
for field in crate::usage::TOKEN_FIELDS.iter().chain(&["cost_usd", "model"]) {
if let Some(value) = object.remove(*field).filter(|value| !value.is_null()) {
usage.insert((*field).into(), value);
}
}
if metered {
object.insert("usage".into(), Value::Object(usage));
}
Ok(row)
})
.collect::<Result<Vec<_>>>()?;
let state = json!({"run":run,"plan":plan,"tasks":array_or_empty(&plan["tasks"]).iter().map(|task| &tasks[string_or_empty(&task["id"])]).collect::<Vec<_>>(),
"branch_tip":branch,"notices":notices,"requests":notices.iter().filter(|row| request_kind(row)).collect::<Vec<_>>(),
"paused_tasks":held,"findings":store.findings(id,None)?,"build_handoffs":handoffs,"attempts":attempts,
"decisions":store.rows("SELECT * FROM decisions WHERE run_id=? ORDER BY id",&[&id])?});
println!("{}", serde_json::to_string_pretty(&state)?);
return Ok(());
}
if run["state"] == "done" && branch.as_deref() == run["tip"].as_str() {
let persisted = notices
.iter()
.rev()
.find(|notice| notice["kind"] == "delivery");
let fallback = json!({"kind":"delivery","run_id":id,"title":plan["goal"],"detail":json!({
"situation":format!("Branch af/{id}, commit {}. Final checks passed.",string_or_empty(&run["tip"])),
"response":"Review the result and decide whether to merge."}).to_string()});
show(persisted.unwrap_or(&fallback))?;
} else {
let situation = if run["state"] == "awaiting_approval" {
"Waiting for plan approval before dispatching work.".into()
} else {
progress(&plan, &tasks, &held)
};
show(
&json!({"kind":"progress","run_id":id,"title":plan["goal"],"detail":json!({
"situation":format!("Plan v{}. {situation}",run["revision"])}).to_string()}),
)?;
}
if run["ref_initialized"] == 1 && branch.as_deref() != run["tip"].as_str() {
println!(
"- The branch differs from the recorded commit ({}).",
branch.as_deref().unwrap_or("branch missing")
);
}
if run["state"] == "approval_rejected" {
println!("- The plan was rejected. Use amend to approve a revised plan.");
}
let pending: Vec<_> = notices
.iter()
.filter(|row| matches!(string_or_empty(&row["state"]), "open" | "received"))
.collect();
if let Some(message) = run["message"]
.as_str()
.filter(|_| !pending.iter().any(|row| row["task_id"].is_null()))
{
println!("- {message}");
}
for notice in &pending {
show(notice)?;
}
for (task, row) in tasks.iter().filter(|(id, row)| {
row["state"] == "blocked"
&& !pending
.iter()
.any(|notice| notice["task_id"] == id.as_str())
}) {
println!(
"- {task} ยท {} โ {}",
string_or_empty(&find_task(&plan, task)["goal"]),
string_or_empty(&row["message"])
);
}
Ok(())
}
pub fn pause(store: &Store, id: &str, task: &str, pause: bool) -> Result<Value> {
let run = store.run(id)?;
let rows = rows(store, id)?;
let row = rows
.get(task)
.filter(|row| row["state"] != "integrated")
.with_context(|| format!("{task} is not an unfinished task in {id}"))?;
let mut detail;
if pause {
store.0.execute(
"INSERT OR IGNORE INTO task_holds VALUES (?,?)",
params![id, task],
)?;
let situation = if matches!(
string_or_empty(&row["state"]),
"building" | "verifying" | "reviewing" | "passed"
) {
"Paused before the next step. An attempt that already started may finish."
} else {
"Task paused."
};
detail = json!({"situation":situation});
} else {
store.0.execute(
"DELETE FROM task_holds WHERE run_id=? AND task_id=?",
params![id, task],
)?;
detail = json!({"situation":"Task unpaused. It continues once it is eligible."});
detail["response"] = json!("Run resume if the run is stopped.");
}
store.notice(
id,
Some(task),
"control",
title(find_task(&store.plan(&run)?, task)),
detail,
None,
)
}
pub fn resolve(
store: &Store,
run: &Value,
task: &str,
note: &str,
request: Option<i64>,
) -> Result<()> {
let id = string_or_empty(&run["id"]);
let row = store
.one(
"SELECT * FROM tasks WHERE run_id=? AND id=? AND state='blocked'",
&[&id, &task],
)?
.with_context(|| format!("{task} is not a blocked task in {id}"))?;
store.decision(
id,
Some(task),
note,
request,
run["revision"].as_i64().unwrap_or(1),
)?;
store.0.execute("UPDATE tasks SET state=retry_state,retry_state=NULL,review_failures=0,gate_failures=0,message=? WHERE run_id=? AND id=?",
params![format!("{}\nDecision: {note}",string_or_empty(&row["message"])),id,task])?;
Ok(())
}
pub fn amend(
store: &Store,
run: &Value,
replacement: &Value,
note: &str,
answered: Option<i64>,
) -> Result<Value> {
let id = string_or_empty(&run["id"]);
if run["state"] == "done" {
bail!("a delivered run cannot be amended; start a new run");
}
if store
.one("SELECT 1 FROM integrations WHERE run_id=?", &[&id])?
.is_some()
{
bail!("resume the interrupted integration before amending the plan");
}
let current = store.plan(run)?;
let by_id = |tasks: &Value| {
array_or_empty(tasks)
.iter()
.map(|task| (string_or_empty(&task["id"]).to_owned(), task.clone()))
.collect::<BTreeMap<_, _>>()
};
let before = by_id(¤t["tasks"]);
let after = by_id(&replacement["tasks"]);
let rows = rows(store, id)?;
let revision = run["revision"].as_i64().unwrap_or(1) + 1;
let previous = store.rows(
&format!("{NOTICES} AND n.state IN ('open','received') ORDER BY n.id"),
&[&id],
)?;
for (task, old) in &before {
let next = after.get(task);
if Some(old) == next {
continue;
}
let row = &rows[task];
if !matches!(string_or_empty(&row["state"]), "pending" | "blocked") {
bail!("{task} already has work in progress or integrated; add a follow-up task");
}
context::supersede(store, id, old, next)?;
if let Some(next) = next {
fn set(value: &Value) -> BTreeSet<&str> {
array_or_empty(value).iter().map(string_or_empty).collect()
}
let restart = set(&old["depends"]) != set(&next["depends"])
|| set(&old["owns"]) != set(&next["owns"]);
store.0.execute("UPDATE tasks SET state='pending',review_failures=0,gate_failures=0,retry_state=NULL,message=?,head=?,review_base=?
WHERE run_id=? AND id=?",params![format!("Plan v{revision} decision: {note}"),
(!restart).then(|| row["head"].as_str()).flatten(),(!restart).then(|| row["review_base"].as_str()).flatten(),id,task])?;
} else {
store.0.execute(
"DELETE FROM tasks WHERE run_id=? AND id=?",
params![id, task],
)?;
store.0.execute(
"DELETE FROM task_holds WHERE run_id=? AND task_id=?",
params![id, task],
)?;
}
}
for task in after.keys().filter(|task| !before.contains_key(*task)) {
store.0.execute(
"INSERT INTO tasks (run_id,id) VALUES (?,?)",
params![id, task],
)?;
}
store.0.execute(
"INSERT INTO plans VALUES (?,?,?)",
params![id, revision, replacement.to_string()],
)?;
let source_task = previous
.iter()
.find(|row| row["id"].as_i64() == answered && answered.is_some())
.and_then(|row| row["task_id"].as_str());
store.decision(id, source_task, note, answered, revision)?;
store.0.execute(
"UPDATE runs SET revision=?,state='running',message=NULL WHERE id=?",
params![revision, id],
)?;
let mut retired = BTreeSet::new();
for row in store.rows(
&format!("{HANDOFFS} AND h.state IN ('captured','pinned','verified','waiting')"),
&[&id],
)? {
let task = string_or_empty(&row["task_id"]);
let attempt = string_or_empty(&row["attempt_id"]);
store.0.execute(
"UPDATE build_handoffs SET state='superseded' WHERE attempt_id=?",
params![attempt],
)?;
store.0.execute(
"UPDATE attempts SET state='superseded' WHERE id=?",
params![attempt],
)?;
if store.0.execute("UPDATE tasks SET state='pending',retry_state=NULL,attempt=NULL WHERE run_id=? AND id=? AND attempt=?",
params![id,task,attempt])? > 0 { retired.insert(task.to_owned()); }
}
for request in previous {
store.transition(
&request,
"superseded",
None,
Some(&format!("The plan moved to v{revision}.")),
)?;
if let Some(task) = request["task_id"].as_str() {
if request["id"].as_i64() != answered
&& request["state"] == "open"
&& !retired.contains(task)
&& before.get(task) == after.get(task)
&& rows.get(task).is_some_and(|row| row["state"] == "blocked")
{
let mut checkpoint = parse(&request["checkpoint"])?;
if checkpoint.is_null() {
checkpoint = json!({"phase":if rows[task]["retry_state"] == "ready_review" {"review"} else {"build"},"head":rows[task]["head"]});
}
store.notice(
id,
Some(task),
string_or_empty(&request["kind"]),
string_or_empty(&request["title"]),
parse(&request["detail"])?,
Some(checkpoint),
)?;
}
}
}
store.notice(
id,
None,
"progress",
string_or_empty(&replacement["goal"]),
json!({
"situation":format!("Plan v{revision} approved."),"response":"Run resume to continue."}),
None,
)
}
pub fn respond(
store: &Store,
id: &str,
request_code: &str,
choice: Option<&str>,
note: Option<&str>,
replacement: Option<&Value>,
) -> Result<Value> {
let (prefix, number) = request_code
.split_once('-')
.context("expected a Y- request code")?;
let prefix = prefix.to_ascii_uppercase();
if !matches!(prefix.as_str(), "Y" | "D" | "A")
|| number.is_empty()
|| number.len() > 18
|| !number.bytes().all(|value| value.is_ascii_digit())
{
bail!("expected a Y- request code");
}
let number: i64 = number.parse()?;
let run = store.run(id)?;
let request = store
.one(&format!("{NOTICES} AND n.id=?"), &[&id, &number])?
.filter(|row| {
request_kind(row)
&& (prefix == "Y"
|| (prefix == "A" && row["kind"] == "action")
|| (prefix == "D" && row["kind"] == "decision"))
})
.with_context(|| format!("{request_code} is not a request in {id}"))?;
let kind = string_or_empty(&request["kind"]);
match (kind, choice) {
("approval", Some("APPROVE" | "REJECT"))
| ("decision", Some("A" | "B"))
| ("action" | "information", None) => {}
("approval", _) => bail!("choose approve or reject"),
("decision", _) => bail!("choose A or B"),
("action", _) => bail!("confirm with --note"),
_ => bail!("supply the answer with --note"),
}
if replacement.is_some() != (choice == Some("B")) {
bail!("choice B requires --plan; choice A retries the current plan");
}
let note = if kind == "approval" && note.is_none() {
if choice == Some("APPROVE") {
"Plan approved."
} else {
"Plan rejected."
}
} else {
note.filter(|note| !note.trim().is_empty())
.context("response note must be a nonempty string")?
};
let reply = json!({"choice":choice,"note":note});
if request["state"] != "open" {
if replacement.is_none()
&& matches!(string_or_empty(&request["state"]), "received" | "resolved")
&& parse(&request["reply"])? == reply
{
if request["state"] == "received" {
return Ok(request);
}
return response_notice(store, &request, string_or_empty(&request["outcome"]), false);
}
bail!("{request_code} is no longer open in {id}");
}
let revision = run["revision"].as_i64().context("missing plan revision")?;
if request["revision"]
.as_i64()
.is_some_and(|old| old != revision)
{
bail!("{request_code} belongs to a previous plan revision");
}
if kind == "approval" {
if run["state"] != "awaiting_approval" {
bail!("this run is not awaiting plan approval");
}
let accepted = choice == Some("APPROVE");
store.0.execute(
"UPDATE runs SET state=? WHERE id=?",
params![
if accepted {
"running"
} else {
"approval_rejected"
},
id
],
)?;
store.decision(id, None, note, Some(number), revision)?;
let outcome = if accepted {
format!("Plan v{revision} approved.")
} else {
"Plan rejection recorded.".into()
};
store.transition(&request, "resolved", Some(&reply), Some(&outcome))?;
return response_notice(store, &request, &outcome, true);
}
let task = request["task_id"].as_str();
if request["checkpoint"].is_null() {
let tasks = rows(store, id)?;
let row = task.and_then(|task| tasks.get(task));
let phase = match row {
Some(row) if row["retry_state"] == "ready_review" => "review",
Some(_) => "build",
None => "final",
};
let head = row.map_or(&run["tip"], |row| &row["head"]);
store.0.execute(
"INSERT INTO request_context VALUES (?,?,?,NULL)",
params![
number,
revision,
json!({"phase":phase,"head":head}).to_string()
],
)?;
}
if let Some(plan) = replacement {
amend(store, &run, plan, note, Some(number))?;
}
if let Some(task) = task {
if replacement.is_none()
|| rows(store, id)?
.get(task)
.is_some_and(|row| row["state"] == "blocked")
{
resolve(store, &store.run(id)?, task, note, Some(number))?;
}
} else if replacement.is_none() {
if run["state"] != "final_failed" {
bail!("{request_code} no longer matches a failed final check");
}
store.decision(id, None, note, Some(number), revision)?;
}
if replacement.is_some() {
let outcome = format!("Choice applied as plan v{}.", revision + 1);
store.transition(&request, "resolved", Some(&reply), Some(&outcome))?;
return response_notice(store, &request, &outcome, true);
}
store.transition(&request, "received", Some(&reply), None)?;
response_notice(
store,
&request,
if kind == "action" {
"Response received. Waiting for the condition to be re-checked."
} else {
"Response received. Waiting to apply it to the next attempt."
},
true,
)
}
fn response_notice(store: &Store, request: &Value, outcome: &str, persist: bool) -> Result<Value> {
let detail = json!({"situation":format!("{} ยท {outcome}",code(request).unwrap_or_default()),"response":"Run resume if the run is stopped."});
if persist {
return store.notice(
string_or_empty(&request["run_id"]),
request["task_id"].as_str(),
"control",
string_or_empty(&request["title"]),
detail,
None,
);
}
let mut notice = request.clone();
notice["kind"] = json!("control");
notice["state"] = json!("info");
notice["detail"] = json!(detail.to_string());
Ok(notice)
}
pub fn resolve_command(store: &Store, run: &Value, task: &str, note: &str) -> Result<Value> {
let id = string_or_empty(&run["id"]);
text(&json!(note), "decision note")?;
if let Some(request) = store
.pending(id, Some(task))?
.filter(|row| row["state"] == "open")
{
return respond(
store,
id,
&code(&request).ok_or_else(|| anyhow!("missing request code"))?,
(request["kind"] == "decision").then_some("A"),
Some(note),
None,
);
}
resolve(store, run, task, note, None)?;
store.notice(
id,
Some(task),
"control",
"Task recovery",
json!({"situation":"Guidance recorded. Run resume to continue."}),
None,
)
}