Files
orch/src/goal.rs
T
johannesandClaude Haiku 4.5 bf609c2e0e Add loop detector, budgets, and live session control
Milestone 8: the loop detector alerts when test failures repeat, budget
caps limit context/cost/wall-time per session with compaction support,
and live control lets you interrupt, message, or kill a running session
from the TUI. Decisions can now be vetoed, which sends hx/message and
rewinds the session to code. All 82 tests pass.

- src/budget.rs: pure functions for active time, budgets and loop detect
- src/runner.rs: Ctl control object polls for commands ~100ms, handles
  interrupt/message/abort/stop at every blocking point, re-runs on
  hints, and compacts when context is high
- src/db.rs: commands table for TUI→runner control
- src/detail.rs, src/goal.rs, src/tui/: loop detector box, budget caps,
  session keys (i/m/s/k/r), goal keys (v for veto), state forcing
- tests/fake_acp_hx.py: slow mode and hx/message, hx/compact log
- examples/machines/task.toml: [budget] with wall_secs, cost, compact_at

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-11-14 12:55:44 +01:00

352 lines
11 KiB
Rust

//! View model of the goal screen (ORCHESTRATOR.md 7.3, `Goal.dc.html`): the goal and its definition of done,
//! the task graph in columns by dependency depth, the critical path, the decisions agents made, the checks.
use crate::view::{Input, Status, hms};
use std::collections::HashMap;
#[derive(Clone, PartialEq, Debug)]
pub struct TaskBox {
pub id: String,
pub name: String,
pub status: Status,
/// `merged`, `queued`, or the state the session is in.
pub detail: String,
pub after: Vec<String>,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Column {
pub label: String,
pub tasks: Vec<TaskBox>,
}
#[derive(Clone, PartialEq, Debug)]
pub struct DecisionView {
pub id: i64,
pub session: String,
pub text: String,
/// The state the decision was made in.
pub state: String,
/// `plan · 13:22`
pub whence: String,
pub vetoed: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CheckState {
Pass,
Fail,
/// Never ran on main.
Unknown,
}
#[derive(Clone, PartialEq, Debug)]
pub struct CheckView {
pub name: String,
pub owner: String,
pub state: CheckState,
}
#[derive(Clone, PartialEq, Debug, Default)]
pub struct GoalView {
pub goal: String,
pub done_when: String,
pub columns: Vec<Column>,
/// `s2 oauth-provider`, in order; the longest chain of unfinished tasks.
pub critical: Vec<String>,
pub decisions: Vec<DecisionView>,
pub checks: Vec<CheckView>,
pub green: usize,
}
/// Length of the dependency chain below a task (0 = no dependencies). Cycles count as 0 instead of looping.
fn depth(id: &str, deps: &HashMap<&str, &Vec<String>>, seen: &mut Vec<String>) -> usize {
if seen.iter().any(|s| s == id) {
return 0;
}
seen.push(id.to_string());
let d = deps.get(id).map_or(0, |ds| {
ds.iter()
.map(|d| 1 + depth(d, deps, seen))
.max()
.unwrap_or(0)
});
seen.pop();
d
}
pub fn build(i: &Input) -> GoalView {
let overview = crate::view::build(i);
let deps: HashMap<&str, &Vec<String>> = i
.tasks
.iter()
.map(|t| (t.id.as_str(), &t.depends_on))
.collect();
let mut boxes: Vec<(usize, TaskBox)> = vec![];
for t in i.tasks {
let row = overview.rows.iter().find(|r| r.id == t.id);
let session = i.sessions.iter().find(|s| s.id == t.id);
let status = row.map_or(Status::Blocked, |r| r.status);
let detail = match (status, session) {
(Status::Done, _) => "merged".to_string(),
(_, Some(s)) if !s.state.is_empty() => match row {
Some(r) if !r.retry.is_empty() => format!("{} {}", s.state, r.retry),
_ => s.state.clone(),
},
_ => "queued".to_string(),
};
boxes.push((
depth(&t.id, &deps, &mut vec![]),
TaskBox {
id: t.id.clone(),
name: t.name.clone(),
status,
detail,
after: t.depends_on.clone(),
},
));
}
let levels = boxes.iter().map(|b| b.0).max().map_or(0, |m| m + 1);
let columns = (0..levels)
.map(|l| Column {
label: format!("level {l}"),
tasks: boxes
.iter()
.filter(|b| b.0 == l)
.map(|b| b.1.clone())
.collect(),
})
.collect();
// critical path: longest chain over unfinished tasks only
let open: Vec<&TaskBox> = boxes
.iter()
.map(|b| &b.1)
.filter(|t| t.status != Status::Done)
.collect();
let mut best: HashMap<&str, (usize, Option<&str>)> = HashMap::new();
let mut order: Vec<&TaskBox> = open.clone();
order.sort_by_key(|t| depth(&t.id, &deps, &mut vec![])); // dependencies first
for t in &order {
let prev = t
.after
.iter()
.filter_map(|d| best.get(d.as_str()).map(|(n, _)| (*n, d.as_str())))
.max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(a.1))); // longest, then lowest id
best.insert(&t.id, (prev.map_or(1, |p| p.0 + 1), prev.map(|p| p.1)));
}
let end = open
.iter()
.map(|t| t.id.as_str())
.max_by(|a, b| best[a].0.cmp(&best[b].0).then(b.cmp(a)));
let mut critical = vec![];
let mut cur = end;
while let Some(id) = cur {
let name = boxes
.iter()
.find(|b| b.1.id == id)
.map_or("", |b| b.1.name.as_str());
critical.push(format!("{id} {name}"));
cur = best[id].1;
}
critical.reverse();
let decisions = i
.decisions
.iter()
.map(|d| DecisionView {
id: d.id,
session: d.session.clone(),
text: d.text.clone(),
state: d.state.clone(),
whence: format!("{} · {}", d.state, &hms(d.at)[..5]),
vetoed: d.vetoed,
})
.collect();
let checks: Vec<CheckView> = i
.checks
.iter()
.map(|c| CheckView {
name: c.name.clone(),
owner: c.owner.clone().unwrap_or_else(|| "-".into()),
state: match c.last_status.as_deref() {
Some("pass") => CheckState::Pass,
Some(_) => CheckState::Fail,
None => CheckState::Unknown,
},
})
.collect();
let green = checks
.iter()
.filter(|c| c.state == CheckState::Pass)
.count();
let done_when = if checks.is_empty() {
"Done = all acceptance checks green on main. None defined yet: orch check NAME CMD."
.to_string()
} else {
format!(
"Done = all {} acceptance checks green on main. The orchestrator re-runs them after every merge.",
checks.len()
)
};
GoalView {
goal: i.goal.unwrap_or("no goal set: orch goal \"…\"").to_string(),
done_when,
columns,
critical,
decisions,
checks,
green,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::{CheckRow, DecisionRow, Session, Task};
use crate::machine::Machine;
fn task(id: &str, name: &str, after: &[&str]) -> Task {
Task {
id: id.into(),
name: name.into(),
subtitle: String::new(),
machine: "task".into(),
depends_on: after.iter().map(|a| a.to_string()).collect(),
}
}
fn session(id: &str, state: &str, status: &str) -> Session {
Session {
id: id.into(),
task_id: id.into(),
branch: "b".into(),
worktree: "/w".into(),
pid: None,
state: state.into(),
status: status.into(),
}
}
fn view(
tasks: &[Task],
sessions: &[Session],
checks: &[CheckRow],
decisions: &[DecisionRow],
) -> GoalView {
let m = HashMap::from([(
"task".to_string(),
Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(),
)]);
build(&Input {
goal: Some("Move login to OAuth2"),
tasks,
sessions,
events: &[],
machines: &m,
needs: &[],
checks,
decisions,
now_ms: 0,
})
}
fn check(name: &str, owner: Option<&str>, st: Option<&str>) -> CheckRow {
CheckRow {
id: 1,
name: name.into(),
cmd: "true".into(),
owner: owner.map(Into::into),
last_status: st.map(Into::into),
last_run_at: None,
}
}
#[test]
fn graph_columns_critical_path_and_checks() {
let tasks = [
task("s1", "schema-migrate", &[]),
task("s2", "oauth-provider", &["s1"]),
task("s3", "auth-middleware", &["s1"]),
task("s4", "rate-limiter", &["s1"]),
task("s5", "docs-update", &["s2", "s3"]),
task("s6", "e2e-tests", &["s3", "s4"]),
];
let sessions = [
session("s1", "merge", "merged"),
session("s2", "test", "running"),
session("s3", "review", "waiting"),
session("s4", "build", "running"),
session("s5", "", "queued"),
session("s6", "plan", "running"),
];
let checks = [
check("build", None, Some("pass")),
check("unit", Some("s2"), Some("fail")),
check("e2e", Some("s6"), None),
];
let decisions = [DecisionRow {
id: 1,
session: "s4".into(),
text: "token bucket".into(),
state: "plan".into(),
at: 0,
vetoed: false,
}];
let v = view(&tasks, &sessions, &checks, &decisions);
fn ids(c: &Column) -> Vec<&str> {
c.tasks.iter().map(|t| t.id.as_str()).collect()
}
assert_eq!(v.columns.len(), 3);
assert_eq!(ids(&v.columns[0]), ["s1"]);
assert_eq!(ids(&v.columns[1]), ["s2", "s3", "s4"]);
assert_eq!(ids(&v.columns[2]), ["s5", "s6"]);
assert_eq!(v.columns[0].label, "level 0");
let s1 = &v.columns[0].tasks[0];
assert_eq!((s1.status, s1.detail.as_str()), (Status::Done, "merged"));
let s3 = &v.columns[1].tasks[1];
assert_eq!(
(s3.status, s3.detail.as_str(), s3.after.clone()),
(Status::Wait, "review", vec!["s1".to_string()])
);
let s5 = &v.columns[2].tasks[0];
assert_eq!((s5.status, s5.detail.as_str()), (Status::Blocked, "queued"));
// longest chain of unfinished tasks; s1 is merged and not part of it
assert_eq!(v.critical, ["s2 oauth-provider", "s5 docs-update"]);
assert_eq!((v.green, v.checks.len()), (1, 3));
assert_eq!(
v.checks.iter().map(|c| c.state).collect::<Vec<_>>(),
[CheckState::Pass, CheckState::Fail, CheckState::Unknown]
);
assert_eq!(v.checks[0].owner, "-");
assert!(
v.done_when
.starts_with("Done = all 3 acceptance checks green on main")
);
assert_eq!(v.decisions[0].session, "s4");
assert!(v.decisions[0].whence.starts_with("plan · "));
}
#[test]
fn empty_and_cyclic_goals_do_not_break() {
let v = view(&[], &[], &[], &[]);
assert!(v.columns.is_empty() && v.critical.is_empty());
assert!(v.done_when.contains("None defined yet"));
// a cycle is a user error, not a hang
let tasks = [task("s1", "a", &["s2"]), task("s2", "b", &["s1"])];
let sessions = [session("s1", "", "queued"), session("s2", "", "queued")];
let v = view(&tasks, &sessions, &[], &[]);
assert_eq!(v.columns.iter().map(|c| c.tasks.len()).sum::<usize>(), 2);
}
#[test]
fn all_done_has_no_critical_path() {
let tasks = [task("s1", "a", &[])];
let sessions = [session("s1", "merge", "merged")];
assert!(view(&tasks, &sessions, &[], &[]).critical.is_empty());
}
}