agengo 0.3.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use crate::{
    context,
    contract::{array_or_empty, string_or_empty, text},
    engine::{find_task, holds, progress, reference, rows, title},
    process::Repo,
    store::{code, notice_json, parse, request_kind, show, Store, HANDOFFS, NOTICES},
};
use anyhow::{anyhow, bail, Context, Result};
use rusqlite::params;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};

pub fn status(repo: &Repo, store: &Store, id: &str, machine: bool) -> Result<()> {
    let mut run = store.run(id)?;
    run["builder_handoff"] = json!(store.handoff_mode(id)?);
    let plan = store.plan(&run)?;
    let tasks = rows(store, id)?;
    let notices = store.rows(&format!("{NOTICES} ORDER BY n.id"), &[&id])?;
    let held = holds(store, id)?;
    let branch = repo.current(&reference(id))?;
    if machine {
        let notices = notices
            .into_iter()
            .map(notice_json)
            .collect::<Result<Vec<_>>>()?;
        let handoffs = store
            .rows(&format!("{HANDOFFS} ORDER BY a.rowid"), &[&id])?
            .into_iter()
            .map(|mut row| {
                row["paths"] = parse(&row["paths"])?;
                row["parents"] = parse(&row["parents"])?;
                let object = row.as_object_mut().unwrap();
                object.remove("request");
                object.remove("result");
                Ok(row)
            })
            .collect::<Result<Vec<_>>>()?;
        let attempts = store
            .rows(
                "SELECT a.*, t.duration_ms, u.attempt_id AS usage_attempt, u.input_tokens, u.output_tokens,
                 u.cache_read_tokens, u.cache_write_tokens, u.cost_usd, u.model
                 FROM attempts a LEFT JOIN attempt_timings t ON t.attempt_id=a.id
                 LEFT JOIN attempt_usage u ON u.attempt_id=a.id
                 WHERE a.run_id=? ORDER BY a.rowid",
                &[&id],
            )?
            .into_iter()
            .map(|mut row| {
                row["request"] = parse(&row["request"])?;
                row["result"] = parse(&row["result"])?;
                if row["duration_ms"].is_null() {
                    row.as_object_mut().unwrap().remove("duration_ms");
                }
                // Fold usage columns into one object; absent means "not reported".
                let object = row.as_object_mut().unwrap();
                let metered = !object.remove("usage_attempt").unwrap_or(Value::Null).is_null();
                let mut usage = serde_json::Map::new();
                for field in crate::usage::TOKEN_FIELDS.iter().chain(&["cost_usd", "model"]) {
                    if let Some(value) = object.remove(*field).filter(|value| !value.is_null()) {
                        usage.insert((*field).into(), value);
                    }
                }
                if metered {
                    object.insert("usage".into(), Value::Object(usage));
                }
                Ok(row)
            })
            .collect::<Result<Vec<_>>>()?;
        let state = json!({"run":run,"plan":plan,"tasks":array_or_empty(&plan["tasks"]).iter().map(|task| &tasks[string_or_empty(&task["id"])]).collect::<Vec<_>>(),
            "branch_tip":branch,"notices":notices,"requests":notices.iter().filter(|row| request_kind(row)).collect::<Vec<_>>(),
            "paused_tasks":held,"findings":store.findings(id,None)?,"build_handoffs":handoffs,"attempts":attempts,
            "decisions":store.rows("SELECT * FROM decisions WHERE run_id=? ORDER BY id",&[&id])?});
        println!("{}", serde_json::to_string_pretty(&state)?);
        return Ok(());
    }
    if run["state"] == "done" && branch.as_deref() == run["tip"].as_str() {
        let persisted = notices
            .iter()
            .rev()
            .find(|notice| notice["kind"] == "delivery");
        let fallback = json!({"kind":"delivery","run_id":id,"title":plan["goal"],"detail":json!({
            "situation":format!("Branch af/{id}, commit {}. Final checks passed.",string_or_empty(&run["tip"])),
            "response":"Review the result and decide whether to merge."}).to_string()});
        show(persisted.unwrap_or(&fallback))?;
    } else {
        let situation = if run["state"] == "awaiting_approval" {
            "Waiting for plan approval before dispatching work.".into()
        } else {
            progress(&plan, &tasks, &held)
        };
        show(
            &json!({"kind":"progress","run_id":id,"title":plan["goal"],"detail":json!({
            "situation":format!("Plan v{}. {situation}",run["revision"])}).to_string()}),
        )?;
    }
    if run["ref_initialized"] == 1 && branch.as_deref() != run["tip"].as_str() {
        println!(
            "- The branch differs from the recorded commit ({}).",
            branch.as_deref().unwrap_or("branch missing")
        );
    }
    if run["state"] == "approval_rejected" {
        println!("- The plan was rejected. Use amend to approve a revised plan.");
    }
    let pending: Vec<_> = notices
        .iter()
        .filter(|row| matches!(string_or_empty(&row["state"]), "open" | "received"))
        .collect();
    if let Some(message) = run["message"]
        .as_str()
        .filter(|_| !pending.iter().any(|row| row["task_id"].is_null()))
    {
        println!("- {message}");
    }
    for notice in &pending {
        show(notice)?;
    }
    for (task, row) in tasks.iter().filter(|(id, row)| {
        row["state"] == "blocked"
            && !pending
                .iter()
                .any(|notice| notice["task_id"] == id.as_str())
    }) {
        println!(
            "- {task} ยท {} โ€” {}",
            string_or_empty(&find_task(&plan, task)["goal"]),
            string_or_empty(&row["message"])
        );
    }
    Ok(())
}

pub fn pause(store: &Store, id: &str, task: &str, pause: bool) -> Result<Value> {
    let run = store.run(id)?;
    let rows = rows(store, id)?;
    let row = rows
        .get(task)
        .filter(|row| row["state"] != "integrated")
        .with_context(|| format!("{task} is not an unfinished task in {id}"))?;
    let mut detail;
    if pause {
        store.0.execute(
            "INSERT OR IGNORE INTO task_holds VALUES (?,?)",
            params![id, task],
        )?;
        let situation = if matches!(
            string_or_empty(&row["state"]),
            "building" | "verifying" | "reviewing" | "passed"
        ) {
            "Paused before the next step. An attempt that already started may finish."
        } else {
            "Task paused."
        };
        detail = json!({"situation":situation});
    } else {
        store.0.execute(
            "DELETE FROM task_holds WHERE run_id=? AND task_id=?",
            params![id, task],
        )?;
        detail = json!({"situation":"Task unpaused. It continues once it is eligible."});
        detail["response"] = json!("Run resume if the run is stopped.");
    }
    store.notice(
        id,
        Some(task),
        "control",
        title(find_task(&store.plan(&run)?, task)),
        detail,
        None,
    )
}

pub fn resolve(
    store: &Store,
    run: &Value,
    task: &str,
    note: &str,
    request: Option<i64>,
) -> Result<()> {
    let id = string_or_empty(&run["id"]);
    let row = store
        .one(
            "SELECT * FROM tasks WHERE run_id=? AND id=? AND state='blocked'",
            &[&id, &task],
        )?
        .with_context(|| format!("{task} is not a blocked task in {id}"))?;
    store.decision(
        id,
        Some(task),
        note,
        request,
        run["revision"].as_i64().unwrap_or(1),
    )?;
    store.0.execute("UPDATE tasks SET state=retry_state,retry_state=NULL,review_failures=0,gate_failures=0,message=? WHERE run_id=? AND id=?",
        params![format!("{}\nDecision: {note}",string_or_empty(&row["message"])),id,task])?;
    Ok(())
}

pub fn amend(
    store: &Store,
    run: &Value,
    replacement: &Value,
    note: &str,
    answered: Option<i64>,
) -> Result<Value> {
    let id = string_or_empty(&run["id"]);
    if run["state"] == "done" {
        bail!("a delivered run cannot be amended; start a new run");
    }
    if store
        .one("SELECT 1 FROM integrations WHERE run_id=?", &[&id])?
        .is_some()
    {
        bail!("resume the interrupted integration before amending the plan");
    }
    let current = store.plan(run)?;
    let by_id = |tasks: &Value| {
        array_or_empty(tasks)
            .iter()
            .map(|task| (string_or_empty(&task["id"]).to_owned(), task.clone()))
            .collect::<BTreeMap<_, _>>()
    };
    let before = by_id(&current["tasks"]);
    let after = by_id(&replacement["tasks"]);
    let rows = rows(store, id)?;
    let revision = run["revision"].as_i64().unwrap_or(1) + 1;
    let previous = store.rows(
        &format!("{NOTICES} AND n.state IN ('open','received') ORDER BY n.id"),
        &[&id],
    )?;
    for (task, old) in &before {
        let next = after.get(task);
        if Some(old) == next {
            continue;
        }
        let row = &rows[task];
        if !matches!(string_or_empty(&row["state"]), "pending" | "blocked") {
            bail!("{task} already has work in progress or integrated; add a follow-up task");
        }
        context::supersede(store, id, old, next)?;
        if let Some(next) = next {
            fn set(value: &Value) -> BTreeSet<&str> {
                array_or_empty(value).iter().map(string_or_empty).collect()
            }
            let restart = set(&old["depends"]) != set(&next["depends"])
                || set(&old["owns"]) != set(&next["owns"]);
            store.0.execute("UPDATE tasks SET state='pending',review_failures=0,gate_failures=0,retry_state=NULL,message=?,head=?,review_base=?
                WHERE run_id=? AND id=?",params![format!("Plan v{revision} decision: {note}"),
                    (!restart).then(|| row["head"].as_str()).flatten(),(!restart).then(|| row["review_base"].as_str()).flatten(),id,task])?;
        } else {
            store.0.execute(
                "DELETE FROM tasks WHERE run_id=? AND id=?",
                params![id, task],
            )?;
            store.0.execute(
                "DELETE FROM task_holds WHERE run_id=? AND task_id=?",
                params![id, task],
            )?;
        }
    }
    for task in after.keys().filter(|task| !before.contains_key(*task)) {
        store.0.execute(
            "INSERT INTO tasks (run_id,id) VALUES (?,?)",
            params![id, task],
        )?;
    }
    store.0.execute(
        "INSERT INTO plans VALUES (?,?,?)",
        params![id, revision, replacement.to_string()],
    )?;
    let source_task = previous
        .iter()
        .find(|row| row["id"].as_i64() == answered && answered.is_some())
        .and_then(|row| row["task_id"].as_str());
    store.decision(id, source_task, note, answered, revision)?;
    store.0.execute(
        "UPDATE runs SET revision=?,state='running',message=NULL WHERE id=?",
        params![revision, id],
    )?;
    let mut retired = BTreeSet::new();
    for row in store.rows(
        &format!("{HANDOFFS} AND h.state IN ('captured','pinned','verified','waiting')"),
        &[&id],
    )? {
        let task = string_or_empty(&row["task_id"]);
        let attempt = string_or_empty(&row["attempt_id"]);
        store.0.execute(
            "UPDATE build_handoffs SET state='superseded' WHERE attempt_id=?",
            params![attempt],
        )?;
        store.0.execute(
            "UPDATE attempts SET state='superseded' WHERE id=?",
            params![attempt],
        )?;
        if store.0.execute("UPDATE tasks SET state='pending',retry_state=NULL,attempt=NULL WHERE run_id=? AND id=? AND attempt=?",
            params![id,task,attempt])? > 0 { retired.insert(task.to_owned()); }
    }
    for request in previous {
        store.transition(
            &request,
            "superseded",
            None,
            Some(&format!("The plan moved to v{revision}.")),
        )?;
        if let Some(task) = request["task_id"].as_str() {
            if request["id"].as_i64() != answered
                && request["state"] == "open"
                && !retired.contains(task)
                && before.get(task) == after.get(task)
                && rows.get(task).is_some_and(|row| row["state"] == "blocked")
            {
                let mut checkpoint = parse(&request["checkpoint"])?;
                if checkpoint.is_null() {
                    checkpoint = json!({"phase":if rows[task]["retry_state"] == "ready_review" {"review"} else {"build"},"head":rows[task]["head"]});
                }
                store.notice(
                    id,
                    Some(task),
                    string_or_empty(&request["kind"]),
                    string_or_empty(&request["title"]),
                    parse(&request["detail"])?,
                    Some(checkpoint),
                )?;
            }
        }
    }
    store.notice(
        id,
        None,
        "progress",
        string_or_empty(&replacement["goal"]),
        json!({
        "situation":format!("Plan v{revision} approved."),"response":"Run resume to continue."}),
        None,
    )
}

pub fn respond(
    store: &Store,
    id: &str,
    request_code: &str,
    choice: Option<&str>,
    note: Option<&str>,
    replacement: Option<&Value>,
) -> Result<Value> {
    let (prefix, number) = request_code
        .split_once('-')
        .context("expected a Y- request code")?;
    let prefix = prefix.to_ascii_uppercase();
    if !matches!(prefix.as_str(), "Y" | "D" | "A")
        || number.is_empty()
        || number.len() > 18
        || !number.bytes().all(|value| value.is_ascii_digit())
    {
        bail!("expected a Y- request code");
    }
    let number: i64 = number.parse()?;
    let run = store.run(id)?;
    let request = store
        .one(&format!("{NOTICES} AND n.id=?"), &[&id, &number])?
        .filter(|row| {
            request_kind(row)
                && (prefix == "Y"
                    || (prefix == "A" && row["kind"] == "action")
                    || (prefix == "D" && row["kind"] == "decision"))
        })
        .with_context(|| format!("{request_code} is not a request in {id}"))?;
    let kind = string_or_empty(&request["kind"]);
    match (kind, choice) {
        ("approval", Some("APPROVE" | "REJECT"))
        | ("decision", Some("A" | "B"))
        | ("action" | "information", None) => {}
        ("approval", _) => bail!("choose approve or reject"),
        ("decision", _) => bail!("choose A or B"),
        ("action", _) => bail!("confirm with --note"),
        _ => bail!("supply the answer with --note"),
    }
    if replacement.is_some() != (choice == Some("B")) {
        bail!("choice B requires --plan; choice A retries the current plan");
    }
    let note = if kind == "approval" && note.is_none() {
        if choice == Some("APPROVE") {
            "Plan approved."
        } else {
            "Plan rejected."
        }
    } else {
        note.filter(|note| !note.trim().is_empty())
            .context("response note must be a nonempty string")?
    };
    let reply = json!({"choice":choice,"note":note});
    if request["state"] != "open" {
        if replacement.is_none()
            && matches!(string_or_empty(&request["state"]), "received" | "resolved")
            && parse(&request["reply"])? == reply
        {
            if request["state"] == "received" {
                return Ok(request);
            }
            return response_notice(store, &request, string_or_empty(&request["outcome"]), false);
        }
        bail!("{request_code} is no longer open in {id}");
    }
    let revision = run["revision"].as_i64().context("missing plan revision")?;
    if request["revision"]
        .as_i64()
        .is_some_and(|old| old != revision)
    {
        bail!("{request_code} belongs to a previous plan revision");
    }
    if kind == "approval" {
        if run["state"] != "awaiting_approval" {
            bail!("this run is not awaiting plan approval");
        }
        let accepted = choice == Some("APPROVE");
        store.0.execute(
            "UPDATE runs SET state=? WHERE id=?",
            params![
                if accepted {
                    "running"
                } else {
                    "approval_rejected"
                },
                id
            ],
        )?;
        store.decision(id, None, note, Some(number), revision)?;
        let outcome = if accepted {
            format!("Plan v{revision} approved.")
        } else {
            "Plan rejection recorded.".into()
        };
        store.transition(&request, "resolved", Some(&reply), Some(&outcome))?;
        return response_notice(store, &request, &outcome, true);
    }
    let task = request["task_id"].as_str();
    if request["checkpoint"].is_null() {
        let tasks = rows(store, id)?;
        let row = task.and_then(|task| tasks.get(task));
        let phase = match row {
            Some(row) if row["retry_state"] == "ready_review" => "review",
            Some(_) => "build",
            None => "final",
        };
        let head = row.map_or(&run["tip"], |row| &row["head"]);
        store.0.execute(
            "INSERT INTO request_context VALUES (?,?,?,NULL)",
            params![
                number,
                revision,
                json!({"phase":phase,"head":head}).to_string()
            ],
        )?;
    }
    if let Some(plan) = replacement {
        amend(store, &run, plan, note, Some(number))?;
    }
    if let Some(task) = task {
        if replacement.is_none()
            || rows(store, id)?
                .get(task)
                .is_some_and(|row| row["state"] == "blocked")
        {
            resolve(store, &store.run(id)?, task, note, Some(number))?;
        }
    } else if replacement.is_none() {
        if run["state"] != "final_failed" {
            bail!("{request_code} no longer matches a failed final check");
        }
        store.decision(id, None, note, Some(number), revision)?;
    }
    if replacement.is_some() {
        let outcome = format!("Choice applied as plan v{}.", revision + 1);
        store.transition(&request, "resolved", Some(&reply), Some(&outcome))?;
        return response_notice(store, &request, &outcome, true);
    }
    store.transition(&request, "received", Some(&reply), None)?;
    response_notice(
        store,
        &request,
        if kind == "action" {
            "Response received. Waiting for the condition to be re-checked."
        } else {
            "Response received. Waiting to apply it to the next attempt."
        },
        true,
    )
}

fn response_notice(store: &Store, request: &Value, outcome: &str, persist: bool) -> Result<Value> {
    let detail = json!({"situation":format!("{} ยท {outcome}",code(request).unwrap_or_default()),"response":"Run resume if the run is stopped."});
    if persist {
        return store.notice(
            string_or_empty(&request["run_id"]),
            request["task_id"].as_str(),
            "control",
            string_or_empty(&request["title"]),
            detail,
            None,
        );
    }
    let mut notice = request.clone();
    notice["kind"] = json!("control");
    notice["state"] = json!("info");
    notice["detail"] = json!(detail.to_string());
    Ok(notice)
}

pub fn resolve_command(store: &Store, run: &Value, task: &str, note: &str) -> Result<Value> {
    let id = string_or_empty(&run["id"]);
    text(&json!(note), "decision note")?;
    if let Some(request) = store
        .pending(id, Some(task))?
        .filter(|row| row["state"] == "open")
    {
        return respond(
            store,
            id,
            &code(&request).ok_or_else(|| anyhow!("missing request code"))?,
            (request["kind"] == "decision").then_some("A"),
            Some(note),
            None,
        );
    }
    resolve(store, run, task, note, None)?;
    store.notice(
        id,
        Some(task),
        "control",
        "Task recovery",
        json!({"situation":"Guidance recorded. Run resume to continue."}),
        None,
    )
}