agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Typed agent assignments (requests) and outcomes (replies).
//!
//! An `Assignment` is what agengo sends to a Builder or Reviewer; it is also
//! stored with each attempt and read back on resume. An `Outcome` is what the
//! agent returns. Replies come from outside agengo (a model or a custom
//! adapter), so `Outcome::parse` checks field types and values at the
//! boundary and names the field that is wrong, instead of letting a missing
//! or misspelled field travel through the engine as `null`.
//!
//! Unknown reply fields are ignored, so adapters may add their own data.

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,
}

/// A build or review request. Field names and JSON layout follow
/// `specs/request.schema.json`.
#[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 {
    /// A request with the fields every role shares; callers fill in the rest.
    // Each argument is a required request field with no sensible default.
    #[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,
        }
    }

    /// Read a request stored with an attempt.
    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)
    }

    /// Ids of the open findings and acceptance criteria sent to a Reviewer.
    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,
}

/// Why a task cannot continue without a person, and what to offer them.
#[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
    }
}

/// How serious a review finding is. Only `Critical` and `High` block a review;
/// `Medium` and `Low` are recorded as advisory and never sent back to the
/// Builder.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Critical,
    /// Also assumed when an adapter omits the field, as adapters written
    /// before severities existed do; their findings blocked, as these do.
    #[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,
}

/// An agent's reply, following `specs/outcome.schema.json`.
#[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>,
    /// `None` when the reply omits the field, which a Reviewer may do when
    /// it only resolves findings.
    #[serde(default)]
    pub findings: Option<Vec<Finding>>,
    #[serde(default)]
    pub finding_resolutions: Vec<Resolution>,
    #[serde(default)]
    pub resolved_conflicts: Vec<String>,
    // Optional echoes of the request; when present they must match it.
    #[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 {
    /// Check an agent reply against the format and the request it answers.
    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<()> {
        // Shape written by agengo 0.3 for a worktree build.
        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(())
    }
}