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
405
406
407
408
409
410
411
412
413
414
415
use crate::adapter::Auth;
use crate::contract::{string_or_empty, STATE_SQL};
use crate::plan::Plan;
use anyhow::{bail, Context, Result};
use rusqlite::{params, types::ValueRef, Connection, ToSql};
use serde_json::{json, Map, Value};
use std::{
    fs::{self, File, OpenOptions},
    path::Path,
    time::Duration,
};

pub fn lock(data: &Path, id: &str) -> Result<File> {
    let directory = data.join("locks");
    fs::create_dir_all(&directory)?;
    // Windows locks need read or write access; append-only access is refused.
    let file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(directory.join(id))?;
    fs2::FileExt::try_lock_exclusive(&file)
        .with_context(|| format!("run {id} already has an active coordinator"))?;
    Ok(file)
}

pub struct Store(pub Connection);

/// Typed view of the per-run settings stored in the `runs` table.
#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
    pub timeout: u64,
    pub jobs: usize,
    pub review_limit: i64,
    pub gate_limit: i64,
    pub revision: i64,
    /// Custom adapter executable; `None` means Claude Code.
    pub agent: Option<String>,
    /// Whether agents use their subscription login or API keys.
    pub auth: Auth,
}

impl Settings {
    pub fn from_row(run: &Value) -> Result<Self> {
        let number = |key: &str| {
            run[key]
                .as_i64()
                .filter(|value| *value > 0)
                .with_context(|| format!("run setting {key} is missing or not positive"))
        };
        Ok(Self {
            timeout: number("timeout")?.unsigned_abs(),
            jobs: usize::try_from(number("jobs")?)?,
            review_limit: number("review_limit")?,
            gate_limit: number("gate_limit")?,
            revision: number("revision")?,
            agent: run["agent"].as_str().map(str::to_owned),
            auth: Auth::from_stored(run["auth"].as_str())?,
        })
    }
}

pub fn parse(value: &Value) -> Result<Value> {
    value
        .as_str()
        .map_or(Ok(Value::Null), |body| Ok(serde_json::from_str(body)?))
}

impl Store {
    pub fn open(data: &Path) -> Result<Self> {
        fs::create_dir_all(data)?;
        let db = Connection::open(data.join("state.sqlite3"))?;
        db.busy_timeout(Duration::from_secs(10))?;
        let version: u32 = db.query_row("PRAGMA user_version", [], |row| row.get(0))?;
        if version > 1 {
            bail!("unsupported agengo state schema {version}; expected at most 1");
        }
        db.execute_batch(STATE_SQL)?;
        Ok(Self(db))
    }

    pub fn atomic<T>(&self, operation: impl FnOnce() -> Result<T>) -> Result<T> {
        self.0.execute_batch("BEGIN IMMEDIATE")?;
        let result = operation().and_then(|value| {
            self.0.execute_batch("COMMIT")?;
            Ok(value)
        });
        if result.is_err() {
            let _ = self.0.execute_batch("ROLLBACK");
        }
        result
    }

    pub fn rows(&self, sql: &str, args: &[&dyn ToSql]) -> Result<Vec<Value>> {
        let mut stmt = self.0.prepare(sql)?;
        let columns: Vec<_> = stmt.column_names().map(str::to_owned).collect();
        let mut rows = stmt.query(args)?;
        let mut results = Vec::new();
        while let Some(row) = rows.next()? {
            let mut result = Map::new();
            for (index, name) in columns.iter().enumerate() {
                let value = match row.get_ref(index)? {
                    ValueRef::Null => Value::Null,
                    ValueRef::Integer(value) => json!(value),
                    ValueRef::Real(value) => json!(value),
                    ValueRef::Text(value) => json!(std::str::from_utf8(value)?),
                    ValueRef::Blob(_) => bail!("unexpected binary column {name}"),
                };
                result.insert(name.clone(), value);
            }
            results.push(Value::Object(result));
        }
        Ok(results)
    }

    pub fn one(&self, sql: &str, args: &[&dyn ToSql]) -> Result<Option<Value>> {
        Ok(self.rows(sql, args)?.into_iter().next())
    }

    pub fn run(&self, id: &str) -> Result<Value> {
        self.one(
            "SELECT runs.*, run_auth.mode AS auth FROM runs \
             LEFT JOIN run_auth ON run_auth.run_id = runs.id WHERE runs.id = ?",
            &[&id],
        )?
        .with_context(|| format!("unknown run: {id}"))
    }

    pub fn plan(&self, run: &Value) -> Result<Plan> {
        let row = self
            .one(
                "SELECT body FROM plans WHERE run_id = ? AND revision = ?",
                &[&string_or_empty(&run["id"]), &run["revision"].as_i64()],
            )?
            .context("missing stored plan")?;
        Plan::from_value(parse(&row["body"])?)
    }

    pub fn handoff_mode(&self, id: &str) -> Result<String> {
        Ok(self
            .one("SELECT mode FROM run_handoff WHERE run_id = ?", &[&id])?
            .map_or_else(
                || "commit".into(),
                |row| string_or_empty(&row["mode"]).into(),
            ))
    }

    pub fn notice(
        &self,
        run: &str,
        task: Option<&str>,
        kind: &str,
        title: &str,
        detail: Value,
        checkpoint: Option<Value>,
    ) -> Result<Value> {
        self.0.execute(
            "INSERT INTO notices (run_id,task_id,kind,title,detail,state) VALUES (?,?,?,?,?,?)",
            params![
                run,
                task,
                kind,
                title,
                detail.to_string(),
                if checkpoint.is_some() { "open" } else { "info" }
            ],
        )?;
        let id = self.0.last_insert_rowid();
        if let Some(checkpoint) = checkpoint {
            self.0.execute(
                "INSERT INTO request_context VALUES (?,?,?,NULL)",
                params![
                    id,
                    self.run(run)?["revision"].as_i64(),
                    checkpoint.to_string()
                ],
            )?;
        }
        self.one(&format!("{NOTICES} AND n.id = ?"), &[&run, &id])?
            .context("missing notice")
    }

    pub fn pending(&self, run: &str, task: Option<&str>) -> Result<Option<Value>> {
        self.one(&format!("{NOTICES} AND n.task_id IS ? AND n.state IN ('open','received') ORDER BY n.id DESC LIMIT 1"),
            &[&run, &task])
    }

    pub fn transition(
        &self,
        request: &Value,
        state: &str,
        reply: Option<&Value>,
        outcome: Option<&str>,
    ) -> Result<()> {
        let id = request["id"].as_i64();
        self.0.execute(
            "UPDATE notices SET state = ?, reply = COALESCE(?,reply) WHERE id = ?",
            params![state, reply.map(Value::to_string), id],
        )?;
        self.0.execute(
            "UPDATE request_context SET outcome = ? WHERE notice_id = ?",
            params![outcome, id],
        )?;
        Ok(())
    }

    pub fn decision(
        &self,
        run: &str,
        task: Option<&str>,
        note: &str,
        source: Option<i64>,
        revision: i64,
    ) -> Result<()> {
        self.0.execute(
            "INSERT INTO decisions (run_id,task_id,note) VALUES (?,?,?)",
            params![run, task, note],
        )?;
        self.0.execute(
            "INSERT INTO decision_sources VALUES (?,?,?)",
            params![self.0.last_insert_rowid(), source, revision],
        )?;
        Ok(())
    }

    pub fn findings(&self, run: &str, task: Option<&str>) -> Result<Vec<Value>> {
        let mut rows = self.rows("SELECT * FROM review_findings WHERE run_id = ? AND (? IS NULL OR task_id = ?) ORDER BY task_id,id",
            &[&run,&task,&task])?;
        for row in &mut rows {
            let detail = parse(&row["detail"])?;
            let resolution = parse(&row["resolution"])?;
            let object = row.as_object_mut().unwrap();
            object.remove("detail");
            if let Value::Object(detail) = detail {
                object.extend(detail);
            }
            object.insert("resolution".into(), resolution);
        }
        Ok(rows)
    }

    /// Store normalized usage for an attempt. A `None` usage records nothing.
    pub fn record_usage(&self, attempt: &str, usage: Option<&Value>) -> Result<()> {
        let Some(usage) = usage else {
            return Ok(());
        };
        self.0.execute(
            "INSERT OR REPLACE INTO attempt_usage
             (attempt_id,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cost_usd,model)
             VALUES (?,?,?,?,?,?,?)",
            params![
                attempt,
                usage["input_tokens"].as_i64(),
                usage["output_tokens"].as_i64(),
                usage["cache_read_tokens"].as_i64(),
                usage["cache_write_tokens"].as_i64(),
                usage["cost_usd"].as_f64(),
                usage["model"].as_str()
            ],
        )?;
        Ok(())
    }

    pub fn record_duration(&self, attempt: &str, elapsed: Duration) -> Result<()> {
        let millis = i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX);
        self.0.execute(
            "INSERT OR IGNORE INTO attempt_timings (attempt_id,duration_ms) VALUES (?,?)",
            params![attempt, millis],
        )?;
        Ok(())
    }
}

pub const NOTICES: &str = "SELECT n.*,c.revision,c.checkpoint,c.outcome FROM notices n LEFT JOIN request_context c ON c.notice_id=n.id WHERE n.run_id=?";
pub const HANDOFFS: &str = "SELECT h.*,a.task_id,a.request,a.result FROM build_handoffs h JOIN attempts a ON a.id=h.attempt_id WHERE a.run_id=?";

pub fn request_kind(row: &Value) -> bool {
    matches!(
        string_or_empty(&row["kind"]),
        "approval" | "decision" | "action" | "information"
    )
}

pub fn code(row: &Value) -> Option<String> {
    row["id"]
        .as_i64()
        .filter(|_| request_kind(row))
        .map(|id| format!("Y-{id:02}"))
}

/// The exact command that answers an open request.
pub fn respond_hint(row: &Value) -> Option<String> {
    let code = code(row)?;
    let run = string_or_empty(&row["run_id"]);
    Some(match string_or_empty(&row["kind"]) {
        "approval" => format!("agengo respond {run} {code} --choice approve (or reject)"),
        "decision" => format!(
            "agengo respond {run} {code} --choice A --note \"<guidance>\" | --choice B --note \"<reason>\" --plan <new-plan>"
        ),
        "action" => format!("agengo respond {run} {code} --note \"<what you did>\""),
        _ => format!("agengo respond {run} {code} --note \"<answer>\""),
    })
}

pub fn notice_json(mut row: Value) -> Result<Value> {
    row["code"] = json!(code(&row));
    row["respond_command"] = json!(respond_hint(&row).filter(|_| row["state"] == "open"));
    row["legacy_code"] = match string_or_empty(&row["kind"]) {
        "action" => json!(format!("A-{:02}", row["id"].as_i64().unwrap_or(0))),
        "decision" => json!(format!("D-{:02}", row["id"].as_i64().unwrap_or(0))),
        _ => Value::Null,
    };
    for field in ["detail", "reply", "checkpoint"] {
        row[field] = parse(&row[field])?;
    }
    Ok(row)
}

pub fn show(row: &Value) -> Result<()> {
    let kind = match string_or_empty(&row["kind"]) {
        "progress" => "PROGRESS",
        "approval" => "APPROVAL",
        "decision" => "DECISION",
        "information" => "QUESTION",
        "action" => "ACTION",
        "control" => "CONTROL",
        "delivery" => "DELIVERED",
        "incident" => "INCIDENT",
        _ => "EVENT",
    };
    let subject = row["task_id"]
        .as_str()
        .unwrap_or(string_or_empty(&row["run_id"]));
    let code = code(row).map_or(String::new(), |code| format!(" · {code}"));
    println!(
        "[{kind}] {subject} · {}{code}",
        line(string_or_empty(&row["title"]))
    );
    let detail = parse(&row["detail"])?;
    if row["state"] == "received" {
        let next = if row["kind"] == "action" {
            "the condition to be re-checked"
        } else {
            "it to be applied to the next attempt"
        };
        println!("- Situation — Response received. Waiting for {next}.");
        return Ok(());
    }
    for (key, label) in [
        ("situation", "Situation"),
        ("recommendation", "Recommendation"),
        ("reason", "Reason"),
    ] {
        if let Some(value) = detail[key].as_str() {
            println!("- {label} — {}", line(value));
        }
    }
    for option in crate::contract::array_or_empty(&detail["options"]) {
        if option["id"] != detail["recommended_choice"] {
            println!(
                "- {} — {}",
                string_or_empty(&option["id"]),
                line(string_or_empty(&option["label"]))
            );
        }
    }
    for (key, label) in [("response", "Response"), ("impact", "Impact")] {
        if let Some(value) = detail[key].as_str() {
            println!("- {label} — {}", line(value));
        }
    }
    if row["state"] == "open" {
        if let Some(hint) = respond_hint(row) {
            println!("- Command — {hint}");
        }
    }
    Ok(())
}

pub fn line(value: &str) -> String {
    value.split_whitespace().collect::<Vec<_>>().join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_are_read_from_a_run_row() -> Result<()> {
        let row = json!({"timeout":900,"jobs":2,"review_limit":3,"gate_limit":2,"revision":4,"agent":null});
        let settings = Settings::from_row(&row)?;
        assert_eq!(
            settings,
            Settings {
                timeout: 900,
                jobs: 2,
                review_limit: 3,
                gate_limit: 2,
                revision: 4,
                agent: None,
                auth: Auth::Api,
            }
        );
        let mut subscription = row.clone();
        subscription["auth"] = json!("subscription");
        assert_eq!(Settings::from_row(&subscription)?.auth, Auth::Subscription);
        let mut broken = row.clone();
        broken["jobs"] = json!(0);
        assert!(Settings::from_row(&broken).is_err());
        broken["jobs"] = Value::Null;
        assert!(Settings::from_row(&broken).is_err());
        Ok(())
    }
}