use crate::{
agent::{Assignment, Outcome, ResolutionStatus, Role, Severity, Status},
contract::{identifier, owns, string_or_empty, text},
plan::{Plan, Task},
process::Repo,
store::{parse, Store},
};
use anyhow::{bail, Result};
use rusqlite::params;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet, HashSet};
pub fn relationships(
repo: &Repo,
store: &Store,
run: &str,
task: &Task,
plan: &Plan,
start: &str,
rows: &BTreeMap<String, Value>,
) -> Result<Value> {
let id = task.id.as_str();
let integrated = store.rows(
"SELECT task_id,sha FROM integrated_tasks WHERE run_id=?",
&[&run],
)?;
let recorded: BTreeMap<_, _> = integrated
.iter()
.map(|row| (string_or_empty(&row["task_id"]), row["sha"].clone()))
.collect();
let edge = |other: &Task, key: &str| {
other
.dependency_context
.iter()
.find(|edge| edge.task_id == key)
.map_or_else(|| json!({}), |edge| json!(edge))
};
let mut depends_on = Vec::new();
let mut seen = HashSet::new();
for dep in task
.depends
.iter()
.map(String::as_str)
.filter(|dep| seen.insert(*dep))
{
let row = &rows[dep];
let sha = recorded.get(dep).cloned().unwrap_or(Value::Null);
let proof = sha.as_str().or_else(|| row["head"].as_str());
let reachable = match proof {
Some(proof) => repo.ancestor(proof, start)?,
None => false,
};
if row["state"] != "integrated" || !reachable {
return Err(crate::failure::DependencyMissing {
task: id.into(),
start: start.into(),
dependency: dep.into(),
}
.into());
}
let mut detail = edge(task, dep);
detail["task_id"] = json!(dep);
detail["state"] = json!("integrated");
detail["verified_ancestor_sha"] = json!(proof);
detail["integration_sha"] = sha;
depends_on.push(detail);
}
let mut required_by = Vec::new();
let mut conflicts_with = Vec::new();
for other in &plan.tasks {
let other_id = other.id.as_str();
let row = &rows[other_id];
if other.depends_on(id) {
let mut detail = json!({"task_id":other_id,"state":row["state"]});
if let Some(value) = edge(other, id).get("needed_for") {
detail["needed_for"] = value.clone();
}
required_by.push(detail);
}
if other_id == id || row["state"] == "integrated" {
continue;
}
let paths: BTreeSet<_> = task
.owns
.iter()
.filter(|path| owns(path, &other.owns))
.chain(other.owns.iter().filter(|path| owns(path, &task.owns)))
.collect();
if !paths.is_empty() {
conflicts_with.push(json!({"task_id":other_id,"paths":paths}));
}
}
let related: Vec<_> = task
.related_to
.iter()
.map(|edge| {
let mut reference = json!(edge);
let id = edge.task_id.as_str();
reference["state"] = rows[id]["state"].clone();
if reference["state"] == "integrated" {
reference["reference_sha"] = recorded.get(id).unwrap_or(&rows[id]["head"]).clone();
}
reference
})
.collect();
Ok(
json!({"depends_on":depends_on,"required_by":required_by,"related_to":related,"conflicts_with":conflicts_with}),
)
}
pub fn decisions(store: &Store, run: &str, task: Option<&str>) -> Result<Vec<Value>> {
let rows = store.rows(
"SELECT d.*,s.request_id,s.revision,n.kind FROM decisions d
LEFT JOIN decision_sources s ON s.decision_id=d.id LEFT JOIN notices n ON n.id=s.request_id
WHERE d.run_id=? AND (d.task_id IS NULL OR d.task_id=?) ORDER BY d.id",
&[&run, &task],
)?;
let mut decisions = Vec::<Value>::new();
for row in rows {
if matches!(string_or_empty(&row["kind"]), "action" | "approval") {
continue;
}
let key = row["request_id"].as_i64().map_or_else(
|| format!("decision-{}", row["id"]),
|id| format!("Y-{id:02}"),
);
let scope = if row["task_id"].is_null() {
json!({"run_id":run})
} else {
json!({"task_id":row["task_id"]})
};
let item =
json!({"id":key,"text":row["note"],"plan_revision":row["revision"],"scope":scope});
if let Some(existing) = decisions.iter_mut().find(|value| value["id"] == key) {
*existing = item;
} else {
decisions.push(item);
}
}
Ok(decisions)
}
pub fn packet(store: &Store, run: &str, task: &Task) -> Result<Value> {
let id = task.id.as_str();
let decisions = decisions(store, run, Some(id))?;
let mut open_findings = Vec::new();
for finding in store
.findings(run, Some(id))?
.into_iter()
.filter(|item| item["state"] == "open")
{
let mut item = json!({"plan_revision":finding["revision"],
"severity":severity(&finding)});
for key in [
"id",
"acceptance_id",
"location",
"reviewed_sha",
"source_attempt_id",
"evidence",
"required_outcome",
] {
item[key] = finding[key].clone();
}
open_findings.push(item);
}
let mut packet =
json!({"acceptance":task.criteria(),"decisions":decisions,"open_findings":open_findings});
if let Some(spec) = crate::spec::assignment_view(store, run, task)? {
packet["spec"] = spec;
}
Ok(packet)
}
pub fn last_failure(store: &Store, run: &str, task: &str) -> Result<Option<Value>> {
let Some(row) = store.one(
"SELECT a.role,a.request,a.result FROM attempts a
WHERE a.run_id=? AND a.task_id=? AND a.state='failed'
AND a.role IN ('build_verify_setup','build_verify','action_verify','integration_setup','integration')
AND a.rowid>COALESCE((SELECT MAX(b.rowid) FROM attempts b
WHERE b.run_id=a.run_id AND b.task_id=a.task_id AND b.role='build' AND b.state='done'),0)
ORDER BY a.rowid DESC LIMIT 1",
&[&run, &task],
)?
else {
return Ok(None);
};
let request = parse(&row["request"])?;
let result = parse(&row["result"])?;
Ok(Some(json!({
"phase": row["role"],
"command": request["command"],
"exit": result["exit"],
"output_tail": last_chars(failure_text(&result), LAST_FAILURE_CHARS),
"head": request["head"],
})))
}
const LAST_FAILURE_CHARS: usize = 4000;
pub(crate) fn failure_text(report: &Value) -> &str {
let stderr = string_or_empty(&report["stderr"]).trim();
if stderr.is_empty() {
string_or_empty(&report["stdout"]).trim()
} else {
stderr
}
}
pub(crate) fn last_chars(text: &str, limit: usize) -> String {
let mut tail: Vec<_> = text.chars().rev().take(limit).collect();
tail.reverse();
tail.into_iter().collect()
}
pub(crate) fn severity(finding: &Value) -> Severity {
Severity::deserialize(&finding["severity"]).unwrap_or_default()
}
pub fn is_blocking(finding: &Value) -> bool {
severity(finding).is_blocking() && finding["refuted"].is_null()
}
pub fn blocks(request: &Assignment, additions: &[Value], resolutions: &[Value]) -> bool {
let resolved = resolutions
.iter()
.filter(|item| item["status"] == "resolved")
.count();
resolved < request.context_ids("open_findings").len() || additions.iter().any(is_blocking)
}
pub fn changes(request: &Assignment, result: &Outcome) -> Result<(Vec<Value>, Vec<Value>)> {
if request.role != Role::Review
|| !matches!(result.status, Status::Pass | Status::ChangesRequested)
{
return Ok((Vec::new(), Vec::new()));
}
let nonempty =
|value: &str, label: &str| -> Result<String> { Ok(text(&json!(value), label)?.to_owned()) };
let acceptance: HashSet<_> = request.context_ids("acceptance").into_iter().collect();
let open: HashSet<_> = request.context_ids("open_findings").into_iter().collect();
let mut additions = Vec::new();
for item in result.findings() {
let id = nonempty(&item.acceptance_id, "finding acceptance id")?;
identifier(&id, "finding acceptance id")?;
if !acceptance.contains(id.as_str()) {
bail!("review finding references unknown acceptance id {id}");
}
let detail = json!({"acceptance_id":id,"severity":item.severity,
"location":nonempty(&item.location, "finding location")?,
"evidence":nonempty(&item.evidence, "finding evidence")?,
"required_outcome":nonempty(&item.required_outcome, "finding required_outcome")?});
if additions.contains(&detail) {
bail!("review reported the same finding twice");
}
additions.push(detail);
}
let blocking = additions.iter().any(is_blocking);
let mut seen = HashSet::new();
let mut closed = 0;
let mut resolutions = Vec::new();
for item in &result.finding_resolutions {
let id = nonempty(&item.id, "finding id")?;
identifier(&id, "finding id")?;
if !open.contains(id.as_str()) || !seen.insert(id.clone()) {
bail!("review resolution does not identify one open finding: {id}");
}
closed += usize::from(item.status == ResolutionStatus::Resolved);
resolutions.push(json!({"id":id,"status":item.status,
"evidence":nonempty(&item.evidence, "resolution evidence")?}));
}
let remaining_or_added = closed < open.len() || blocking;
if result.status == Status::Pass && remaining_or_added {
bail!("review pass requires all open findings to be resolved and no new critical or high findings");
}
if result.status == Status::ChangesRequested && result.findings.is_some() && !remaining_or_added
{
bail!("changes_requested requires new critical or high findings, or still-open findings");
}
Ok((additions, resolutions))
}
pub fn save(
store: &Store,
request: &Assignment,
additions: Vec<Value>,
resolutions: Vec<Value>,
) -> Result<()> {
let run = request.run_id.as_str();
let task = request.task.id.as_str();
if !additions.is_empty() {
let mut number: i64 = store.0.query_row(
"SELECT COUNT(*) FROM review_findings WHERE run_id=? AND task_id=?",
params![run, task],
|row| row.get(0),
)?;
for detail in additions {
number += 1;
store.0.execute(
"INSERT INTO review_findings VALUES (?,?,?,?,?,?,?,?,NULL)",
params![
run,
task,
format!("F-{number:02}"),
if is_blocking(&detail) {
"open"
} else {
"advisory"
},
detail.to_string(),
request.attempt_id,
request.head,
request.plan_revision
],
)?;
}
}
for resolution in resolutions {
let evidence = json!({"attempt_id":request.attempt_id,"reviewed_sha":request.head,
"plan_revision":request.plan_revision,"evidence":resolution["evidence"]});
store.0.execute(
"UPDATE review_findings SET state=?,resolution=? WHERE run_id=? AND task_id=? AND id=?",
params![
string_or_empty(&resolution["status"]),
evidence.to_string(),
run,
task,
string_or_empty(&resolution["id"])
],
)?;
}
Ok(())
}
pub fn supersede(store: &Store, id: &str, before: &Task, after: Option<&Task>) -> Result<()> {
let task = before.id.as_str();
let old = before.criteria();
let new = after.map(Task::criteria).unwrap_or_default();
let changed = after.is_none_or(|after| before.owns != after.owns);
for finding in store
.findings(id, Some(task))?
.iter()
.filter(|value| value["state"] == "open")
{
let criterion = &finding["acceptance_id"];
if changed
|| old.iter().find(|value| value.id == *criterion)
!= new.iter().find(|value| value.id == *criterion)
{
store.0.execute("UPDATE review_findings SET state='superseded' WHERE run_id=? AND task_id=? AND id=?",
params![id, task, string_or_empty(&finding["id"])])?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::validate_plan;
use anyhow::Context;
use std::path::PathBuf;
fn request(open: &[&str]) -> Result<Assignment> {
let plan = Plan::from_value(validate_plan(json!({
"goal": "Ship", "final_verify": [["true"]],
"tasks": [{"id": "a", "goal": "Build A", "owns": ["a"], "acceptance": ["Done"], "verify": [["true"]]}]
}))?)?;
let mut request = Assignment::new(
"att-1",
1,
Role::Review,
"run",
&plan,
plan.task("a")?,
"abc",
PathBuf::from("/tmp/w"),
);
request.context = json!({"acceptance":[{"id":"AC-1"}],
"open_findings":open.iter().map(|id| json!({"id":id})).collect::<Vec<_>>()});
Ok(request)
}
fn finding(severity: Option<&str>) -> Value {
let mut item = json!({"acceptance_id":"AC-1","location":"a.rs","evidence":"e",
"required_outcome":"r"});
if let Some(severity) = severity {
item["severity"] = json!(severity);
}
item
}
fn review(
open: &[&str],
status: &str,
findings: Vec<Value>,
) -> Result<(Vec<Value>, Vec<Value>)> {
let request = request(open)?;
let reply =
json!({"status":status,"summary":"s","findings":findings,"finding_resolutions":[]});
changes(&request, &Outcome::parse(&reply, &request)?)
}
#[test]
fn pass_may_carry_advisory_findings() -> Result<()> {
let (added, _) = review(
&[],
"pass",
vec![finding(Some("medium")), finding(Some("low"))],
)?;
assert_eq!(added.len(), 2);
assert!(added.iter().all(|item| !is_blocking(item)));
Ok(())
}
#[test]
fn pass_rejects_blocking_findings() {
for severity in [Some("critical"), Some("high"), None] {
assert!(review(&[], "pass", vec![finding(severity)]).is_err());
}
}
#[test]
fn changes_requested_needs_a_blocking_reason() -> Result<()> {
assert!(review(&[], "changes_requested", vec![finding(Some("low"))]).is_err());
let (added, _) = review(&[], "changes_requested", vec![finding(None)])?;
assert_eq!(added[0]["severity"], "high");
review(&["F-01"], "changes_requested", vec![finding(Some("low"))])?;
Ok(())
}
#[test]
fn failure_text_prefers_stderr_and_last_chars_counts_characters() {
assert_eq!(
failure_text(&json!({"stdout":" out ","stderr":" err\n"})),
"err"
);
assert_eq!(failure_text(&json!({"stdout":" out\n","stderr":""})), "out");
assert_eq!(failure_text(&json!({"exit":null})), "");
assert_eq!(last_chars("héllo", 3), "llo");
assert_eq!(last_chars("ab", 4), "ab");
}
#[test]
fn stored_findings_without_severity_block() {
assert!(is_blocking(&json!({"acceptance_id":"AC-1"})));
assert!(!is_blocking(&json!({"severity":"medium"})));
}
fn attempt_store() -> Result<Store> {
let db = rusqlite::Connection::open_in_memory()?;
db.execute_batch(crate::contract::STATE_SQL)?;
Ok(Store(db))
}
fn record(store: &Store, id: &str, task: &str, role: &str, state: &str) -> Result<()> {
let request = json!({"command":["check",id],"head":format!("head-{id}")});
let result = json!({"exit":1,"stderr":format!("boom {id}"),"stdout":""});
store.0.execute(
"INSERT INTO attempts VALUES (?,?,?,?,?,?,?)",
params![
id,
"r",
task,
role,
state,
request.to_string(),
result.to_string()
],
)?;
Ok(())
}
#[test]
fn last_failure_is_only_the_failure_newer_than_the_latest_build() -> Result<()> {
let store = attempt_store()?;
assert!(last_failure(&store, "r", "a")?.is_none());
record(&store, "f1", "a", "build_verify", "failed")?;
let shown = last_failure(&store, "r", "a")?.context("failure before any build")?;
assert_eq!(shown["command"], json!(["check", "f1"]));
record(&store, "b1", "a", "build", "done")?;
assert!(last_failure(&store, "r", "a")?.is_none());
record(&store, "other", "b", "integration", "failed")?;
record(&store, "review1", "a", "review", "failed")?;
record(&store, "b2", "a", "build", "failed")?;
assert!(last_failure(&store, "r", "a")?.is_none());
record(&store, "f2", "a", "integration", "failed")?;
let shown = last_failure(&store, "r", "a")?.context("failure after latest build")?;
assert_eq!(shown["phase"], "integration");
assert_eq!(shown["command"], json!(["check", "f2"]));
assert_eq!(shown["head"], "head-f2");
assert_eq!(shown["output_tail"], "boom f2");
store.0.execute(
"INSERT INTO attempts VALUES (?,?,?,?,?,?,?)",
params![
"dup1",
"r",
"a",
"integration_duplicates",
"failed",
json!({"head":"head-dup1"}).to_string(),
json!({"exit":null,"stderr":"duplicates"}).to_string()
],
)?;
let shown =
last_failure(&store, "r", "a")?.context("failure before a newer non-check row")?;
assert_eq!(shown["phase"], "integration");
assert_eq!(shown["command"], json!(["check", "f2"]));
let passed = json!({"command":["check","ok1"],"head":"head-ok1"});
let passed_result = json!({"exit":0,"stderr":"","stdout":"fine"});
store.0.execute(
"INSERT INTO attempts VALUES (?,?,?,?,?,?,?)",
params![
"ok1",
"r",
"a",
"integration_setup",
"ok",
passed.to_string(),
passed_result.to_string()
],
)?;
let shown =
last_failure(&store, "r", "a")?.context("failure before a newer passing check")?;
assert_eq!(shown["phase"], "integration");
assert_eq!(shown["command"], json!(["check", "f2"]));
assert_eq!(shown["exit"], 1);
assert_eq!(shown["head"], "head-f2");
assert_eq!(shown["output_tail"], "boom f2");
for (id, state) in [("b3", "interrupted"), ("b4", "error"), ("b5", "blocked")] {
record(&store, id, "a", "build", state)?;
let shown = last_failure(&store, "r", "a")?
.with_context(|| format!("failure after the {state} build"))?;
assert_eq!(shown["command"], json!(["check", "f2"]));
}
record(&store, "b6", "a", "build", "done")?;
assert!(last_failure(&store, "r", "a")?.is_none());
Ok(())
}
}