agengo 0.4.0

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
use crate::{
    agent::{Assignment, Outcome, ResolutionStatus, Role, Severity, Status},
    contract::{identifier, owns, string_or_empty, text},
    plan::{Plan, Task},
    process::Repo,
    store::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());
        if row["state"] != "integrated"
            || proof.is_none()
            || !repo.ancestor(proof.unwrap(), start)?
        {
            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}),
    )
}

/// Decisions that apply to the run, and to `task` when given.
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)
}

/// Severity of a stored finding. Findings recorded before severities existed
/// have none and count as `high`, which blocks, as they did then. Metrics
/// use the same rule.
pub(crate) fn severity(finding: &Value) -> Severity {
    Severity::deserialize(&finding["severity"]).unwrap_or_default()
}

/// Whether a stored or newly reported finding blocks the review. A finding the
/// verifier refuted does not.
pub fn is_blocking(finding: &Value) -> bool {
    severity(finding).is_blocking() && finding["refuted"].is_null()
}

/// Whether a review's changes still block the task: an open finding was not
/// resolved, or a new finding blocks.
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 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");
        // A still-open finding is reason enough, alongside advisory ones.
        review(&["F-01"], "changes_requested", vec![finding(Some("low"))])?;
        Ok(())
    }

    #[test]
    fn stored_findings_without_severity_block() {
        assert!(is_blocking(&json!({"acceptance_id":"AC-1"})));
        assert!(!is_blocking(&json!({"severity":"medium"})));
    }
}