use crate::{
contract::text,
plan::{Plan, Task},
};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Build,
Review,
}
impl Role {
pub fn as_str(self) -> &'static str {
match self {
Role::Build => "build",
Role::Review => "review",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Handoff {
Commit,
Worktree,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Assignment {
pub schema_version: u32,
pub message_id: String,
pub attempt_id: String,
pub plan_revision: i64,
pub role: Role,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub review_scope: Option<String>,
pub run_id: String,
pub task: Task,
pub project_goal: String,
#[serde(default)]
pub feedback: Option<String>,
pub integration_sha: String,
pub head: String,
#[serde(default)]
pub base: Option<String>,
pub worktree: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub builder_handoff: Option<Handoff>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merge_parent: Option<String>,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub relationships: Value,
#[serde(default)]
pub decisions: Value,
#[serde(default)]
pub context: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub human_request_id: Option<i64>,
}
impl Assignment {
#[allow(clippy::too_many_arguments)]
pub fn new(
attempt: &str,
revision: i64,
role: Role,
run: &str,
plan: &Plan,
task: &Task,
head: &str,
worktree: PathBuf,
) -> Self {
Self {
schema_version: 1,
message_id: attempt.into(),
attempt_id: attempt.into(),
plan_revision: revision,
role,
review_scope: None,
run_id: run.into(),
task: task.clone(),
project_goal: plan.goal.clone(),
feedback: None,
integration_sha: head.into(),
head: head.into(),
base: None,
worktree,
builder_handoff: None,
branch: None,
merge_parent: None,
relationships: Value::Null,
decisions: Value::Array(Vec::new()),
context: Value::Null,
human_request_id: None,
}
}
pub fn from_value(value: &Value) -> Result<Self> {
Self::deserialize(value).context("stored assignment does not match the request format")
}
pub fn to_value(&self) -> Value {
serde_json::to_value(self).expect("an assignment always serializes to JSON")
}
pub fn is_worktree_build(&self) -> bool {
self.role == Role::Build && self.builder_handoff == Some(Handoff::Worktree)
}
pub fn context_ids(&self, key: &str) -> Vec<&str> {
self.context[key]
.as_array()
.map(|items| {
items
.iter()
.filter_map(|item| item["id"].as_str())
.collect()
})
.unwrap_or_default()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Ready,
Done,
Blocked,
Pass,
ChangesRequested,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BlockerKind {
Action,
Decision,
Information,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Choice {
A,
B,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Blocker {
pub kind: BlockerKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recommendation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recommended_choice: Option<Choice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub alternative: Option<String>,
}
impl Blocker {
pub fn decision(recommendation: impl Into<String>) -> Self {
Self {
kind: BlockerKind::Decision,
recommendation: Some(recommendation.into()),
reason: None,
recommended_choice: None,
alternative: None,
}
}
pub fn action(recommendation: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
kind: BlockerKind::Action,
recommendation: Some(recommendation.into()),
reason: Some(reason.into()),
recommended_choice: None,
alternative: None,
}
}
pub fn alternative(mut self, alternative: impl Into<String>) -> Self {
self.alternative = Some(alternative.into());
self
}
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn recommend_b(mut self) -> Self {
self.recommended_choice = Some(Choice::B);
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Critical,
#[default]
High,
Medium,
Low,
}
impl Severity {
pub fn is_blocking(self) -> bool {
matches!(self, Self::Critical | Self::High)
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Finding {
pub acceptance_id: String,
#[serde(default)]
pub severity: Severity,
pub location: String,
pub evidence: String,
pub required_outcome: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ResolutionStatus {
Open,
Resolved,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Resolution {
pub id: String,
pub status: ResolutionStatus,
pub evidence: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Outcome {
pub status: Status,
#[serde(default)]
pub head: Option<String>,
pub summary: String,
#[serde(default)]
pub blocker: Option<Blocker>,
#[serde(default)]
pub findings: Option<Vec<Finding>>,
#[serde(default)]
pub finding_resolutions: Vec<Resolution>,
#[serde(default)]
pub resolved_conflicts: Vec<String>,
#[serde(default)]
in_reply_to: Option<Value>,
#[serde(default)]
attempt_id: Option<Value>,
#[serde(default)]
run_id: Option<Value>,
#[serde(default)]
plan_revision: Option<Value>,
#[serde(default)]
task_id: Option<Value>,
}
impl Outcome {
pub fn parse(reply: &Value, request: &Assignment) -> Result<Self> {
let outcome = Self::deserialize(reply)
.map_err(|error| anyhow::anyhow!("invalid agent reply: {error}"))?;
text(&Value::String(outcome.summary.clone()), "agent summary")?;
let attempt = Value::String(request.attempt_id.clone());
for (echo, expected) in [
(&outcome.in_reply_to, attempt.clone()),
(&outcome.attempt_id, attempt),
(&outcome.run_id, Value::String(request.run_id.clone())),
(&outcome.plan_revision, Value::from(request.plan_revision)),
(&outcome.task_id, Value::String(request.task.id.clone())),
] {
if echo.as_ref().is_some_and(|value| *value != expected) {
bail!("agent reply belongs to a different assignment");
}
}
Ok(outcome)
}
pub fn findings(&self) -> &[Finding] {
self.findings.as_deref().unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::validate_plan;
use serde_json::json;
fn assignment() -> 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",
2,
Role::Review,
"run",
&plan,
plan.task("a")?,
"abc",
PathBuf::from("/tmp/w"),
);
request.base = Some("base".into());
Ok(request)
}
#[test]
fn assignments_round_trip_through_storage() -> Result<()> {
let request = assignment()?;
let stored = request.to_value();
assert_eq!(stored["role"], "review");
assert_eq!(stored["feedback"], Value::Null);
assert!(stored.get("builder_handoff").is_none());
assert_eq!(Assignment::from_value(&stored)?.to_value(), stored);
Ok(())
}
#[test]
fn requests_stored_by_earlier_versions_are_read() -> Result<()> {
let stored = json!({"schema_version":1,"message_id":"m","attempt_id":"m","plan_revision":1,
"role":"build","run_id":"demo","project_goal":"Ship","feedback":null,
"integration_sha":"t","head":"h","base":"t","worktree":"/w/build/m",
"builder_handoff":"worktree","branch":"af-work/demo/a/m","merge_parent":"t",
"task":{"id":"a","goal":"A","depends":[],"owns":["a"],"acceptance":["Done"],"setup":[],"verify":[["true"]]},
"relationships":{"depends_on":[]},"decisions":[{"id":1,"note":"n"}],
"context":{"acceptance":[{"id":"AC-1","text":"Done"}],"open_findings":[]},"human_request_id":3});
let request = Assignment::from_value(&stored)?;
assert!(request.is_worktree_build());
assert_eq!(request.merge_parent.as_deref(), Some("t"));
assert_eq!(request.context_ids("acceptance"), ["AC-1"]);
assert_eq!(request.to_value(), stored);
Ok(())
}
#[test]
fn replies_are_checked_at_the_boundary() -> Result<()> {
let request = assignment()?;
let outcome = Outcome::parse(
&json!({"status":"changes_requested","head":"abc","summary":"Needs work","attempt_id":"att-1",
"findings":[{"acceptance_id":"AC-1","location":"a","evidence":"e","required_outcome":"r"}],
"blocker":null,"extra":"ignored"}),
&request,
)?;
assert_eq!(outcome.status, Status::ChangesRequested);
assert_eq!(outcome.findings().len(), 1);
assert_eq!(outcome.findings()[0].severity, Severity::High);
assert!(outcome.finding_resolutions.is_empty());
let error = |reply: Value| Outcome::parse(&reply, &request).unwrap_err().to_string();
assert!(error(json!({"status":"finished","summary":"x"}))
.contains("unknown variant `finished`"));
assert!(error(json!({"status":"pass"})).contains("summary"));
assert!(error(json!({"status":"pass","summary":" "})).contains("agent summary"));
assert!(error(json!({"status":"pass","summary":"x","findings":{}}))
.contains("invalid agent reply"));
assert!(error(
json!({"status":"pass","summary":"x","findings":[{"acceptance_id":"AC-1",
"severity":"blocker","location":"a","evidence":"e","required_outcome":"r"}]})
)
.contains("unknown variant `blocker`"));
assert!(
error(json!({"status":"blocked","summary":"x","blocker":{"kind":"maybe"}}))
.contains("unknown variant")
);
assert!(
error(json!({"status":"pass","summary":"x","run_id":"other"}))
.contains("different assignment")
);
assert!(
error(json!({"status":"pass","summary":"x","plan_revision":1}))
.contains("different assignment")
);
Ok(())
}
}