agengo 0.5.1

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
//! `.agengo/config.yaml`: the few choices a repository keeps for agengo.
//! Every key is optional and the file may be missing.

use anyhow::{bail, Context, Result};
use serde::Deserialize;
use serde_yaml_ng::{Mapping, Value};
use std::{collections::BTreeMap, fs, path::Path, sync::OnceLock};

pub const PATH: &str = ".agengo/config.yaml";

#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// The agent to use: `claude`, `codex`, `agy`, the path of a custom
    /// adapter, or `auto` to use the only one installed.
    #[serde(default)]
    pub agent: Option<String>,
    /// For the roles that plan, specify, review and verify.
    #[serde(default)]
    pub think: Tier,
    /// For the role that builds.
    #[serde(default)]
    pub build: Tier,
    /// How far agengo goes to confine the agents it starts; see `Sandbox`.
    #[serde(default)]
    pub sandbox: Sandbox,
    /// Environment variables to pass to agents on top of the short list
    /// agengo keeps when `sandbox` is not `off`.
    #[serde(default)]
    pub sandbox_env: Vec<String>,
    /// Folders plan commands may write besides the worktree, on top of the
    /// usual package caches (`~/.cargo`, `~/.npm`, `~/.cache`). `~/` stands
    /// for the home folder.
    #[serde(default)]
    pub sandbox_write: Vec<String>,
    /// Whether `verify`, `final_verify` and the other checks may use the
    /// network when plan commands run in a sandbox. `setup` always may.
    #[serde(default)]
    pub sandbox_check_network: bool,
}

/// How far agengo goes to confine the agents it starts.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum Sandbox {
    /// Start agents as before: no OS sandbox, the whole environment passes.
    Off,
    /// Use the agent's OS sandbox where agengo can switch it on, say so where
    /// it cannot, and pass only a short list of environment variables.
    #[default]
    Auto,
    /// As `auto`, but refuse to start an agent whose sandbox agengo cannot
    /// enforce.
    Strict,
}

impl Sandbox {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Auto => "auto",
            Self::Strict => "strict",
        }
    }
}

/// Set once from `--sandbox`; wins over `sandbox:` in the file.
static OVERRIDE: OnceLock<Sandbox> = OnceLock::new();

pub fn override_sandbox(mode: Sandbox) {
    let _ = OVERRIDE.set(mode);
}

/// What a tier asks of the agent. All of it is optional: what is not set is
/// left to the agent's own default.
#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Tier {
    /// A model name, passed to the agent as it is written; agengo does not
    /// check it.
    #[serde(default)]
    pub model: Option<String>,
    #[serde(default)]
    pub effort: Option<Effort>,
    /// Model names for particular agents (`claude`, `codex`, `agy`), for when
    /// the platform changes and the names do not carry over. They win over
    /// `model`.
    #[serde(default)]
    pub models: BTreeMap<String, String>,
}

/// How hard the model should think, on one scale for every agent; each
/// agent's driver turns it into that agent's own setting.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
    Low,
    Medium,
    High,
    Max,
}

impl Effort {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Max => "max",
        }
    }
}

/// The tier a role belongs to and what that tier asks of the agent.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Pick {
    pub tier: &'static str,
    pub model: Option<String>,
    pub effort: Option<Effort>,
    pub sandbox: Sandbox,
}

impl Config {
    /// Roles that plan, specify, review or verify think; the Builder builds.
    pub fn tier_of(role: &str) -> &'static str {
        if role == "build" {
            "build"
        } else {
            "think"
        }
    }

    /// What to ask of `agent` (`claude`, `codex`, `agy` or a custom
    /// adapter's path) for `role`.
    pub fn pick(&self, role: &str, agent: &str) -> Pick {
        let tier = Self::tier_of(role);
        let settings = if tier == "build" {
            &self.build
        } else {
            &self.think
        };
        Pick {
            tier,
            model: settings
                .models
                .get(agent)
                .or(settings.model.as_ref())
                .cloned(),
            effort: settings.effort,
            sandbox: self.sandbox,
        }
    }

    /// One line saying what each configured tier asks for, `None` when
    /// nothing is configured.
    pub fn describe(&self, agent: &str) -> Option<String> {
        let parts: Vec<String> = [("think", "plan"), ("build", "build")]
            .iter()
            .filter_map(|(label, role)| {
                let pick = self.pick(role, agent);
                let detail = match (pick.model, pick.effort) {
                    (None, None) => return None,
                    (Some(model), None) => model,
                    (None, Some(effort)) => format!("effort {}", effort.as_str()),
                    (Some(model), Some(effort)) => format!("{model}, effort {}", effort.as_str()),
                };
                Some(format!("{label}: {detail}"))
            })
            .collect();
        (!parts.is_empty()).then(|| parts.join(" ยท "))
    }
}

pub fn load(root: &Path) -> Result<Config> {
    let path = root.join(PATH);
    let text = match fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            let mut config = Config::default();
            if let Some(mode) = OVERRIDE.get() {
                config.sandbox = *mode;
            }
            return Ok(config);
        }
        Err(error) => return Err(error).with_context(|| format!("cannot read {PATH}")),
    };
    // An empty file, or one holding only comments, is no configuration.
    let mut config = if text.trim().is_empty() || serde_yaml_ng::from_str::<Value>(&text)?.is_null()
    {
        Config::default()
    } else {
        serde_yaml_ng::from_str(&text).with_context(|| format!("invalid {PATH}"))?
    };
    if let Some(mode) = OVERRIDE.get() {
        config.sandbox = *mode;
    }
    Ok(config)
}

/// Set `agent` (or remove it with `None`), keeping any other key. Comments in
/// the file are not kept.
pub fn set_agent(root: &Path, agent: Option<&str>) -> Result<()> {
    set(root, "agent", agent)
}

/// The keys `agengo config set` accepts: `agent`, `think.model`,
/// `think.effort`, `think.models.NAME` and the same for `build`.
fn key_path(key: &str) -> Result<Vec<&str>> {
    let parts: Vec<&str> = key.split('.').collect();
    let valid = match parts.as_slice() {
        ["agent"] | ["sandbox"] => true,
        ["think" | "build", "model" | "effort"] => true,
        ["think" | "build", "models", name] => !name.is_empty(),
        _ => false,
    };
    if !valid {
        bail!("unknown setting `{key}`; use agent, sandbox, think.model, think.effort, build.model, build.effort, think.models.NAME or build.models.NAME");
    }
    Ok(parts)
}

/// Set `key` to `value`, or remove it with `None`, keeping the other keys.
/// The result is checked as `load` would, so a bad value is refused before
/// anything is written. Comments in the file are not kept.
pub fn set(root: &Path, key: &str, value: Option<&str>) -> Result<()> {
    let parts = key_path(key)?;
    let path = root.join(PATH);
    let mut document = match fs::read_to_string(&path) {
        Ok(text) if !text.trim().is_empty() => {
            serde_yaml_ng::from_str::<Value>(&text).with_context(|| format!("invalid {PATH}"))?
        }
        _ => Value::Null,
    };
    if document.is_null() {
        document = Value::Mapping(Mapping::new());
    }
    let mut map = match &mut document {
        Value::Mapping(map) => map,
        _ => bail!("{PATH} is not a YAML mapping"),
    };
    let (last, parents) = parts.split_last().expect("a key has a part");
    for part in parents {
        let entry = map
            .entry(Value::String((*part).into()))
            .or_insert_with(|| Value::Mapping(Mapping::new()));
        if entry.is_null() {
            *entry = Value::Mapping(Mapping::new());
        }
        map = match entry {
            Value::Mapping(inner) => inner,
            _ => bail!("{PATH}: `{part}` is not a mapping"),
        };
    }
    let name = Value::String((*last).into());
    match value {
        Some(value) => {
            map.insert(name, Value::String(value.into()));
        }
        None => {
            map.remove(&name);
        }
    }
    let text = serde_yaml_ng::to_string(&document)?;
    serde_yaml_ng::from_str::<Config>(&text)
        .with_context(|| format!("`{value:?}` is not valid for {key}"))?;
    fs::create_dir_all(path.parent().context("config path has a parent")?)?;
    fs::write(&path, text).with_context(|| format!("cannot write {PATH}"))
}

/// `agengo config`: what the repository asks for, one line per setting.
pub fn describe(root: &Path) -> Result<Vec<String>> {
    let config = load(root)?;
    let tier = |name: &str, tier: &Tier| {
        let mut line = format!(
            "{name}: model {}, effort {}",
            tier.model.as_deref().unwrap_or("(agent's own)"),
            tier.effort.map_or("(agent's own)", Effort::as_str)
        );
        for (agent, model) in &tier.models {
            line.push_str(&format!(" ยท {agent}: {model}"));
        }
        line
    };
    Ok(vec![
        format!(
            "agent: {}",
            config
                .agent
                .as_deref()
                .unwrap_or("(none; see `agengo agent`)")
        ),
        tier("think", &config.think),
        tier("build", &config.build),
        format!(
            "sandbox: {}{}",
            config.sandbox.as_str(),
            if config.sandbox_env.is_empty() {
                String::new()
            } else {
                format!(" ยท extra environment: {}", config.sandbox_env.join(", "))
            }
        ),
    ])
}

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

    #[test]
    fn a_missing_empty_or_commented_file_is_no_configuration() -> Result<()> {
        let dir = tempfile::tempdir()?;
        assert_eq!(load(dir.path())?, Config::default());
        fs::create_dir_all(dir.path().join(".agengo"))?;
        for text in ["", "\n", "# nothing yet\n"] {
            fs::write(dir.path().join(PATH), text)?;
            assert_eq!(load(dir.path())?, Config::default(), "{text:?}");
        }
        Ok(())
    }

    #[test]
    fn the_agent_is_read_and_unknown_keys_are_refused() -> Result<()> {
        let dir = tempfile::tempdir()?;
        fs::create_dir_all(dir.path().join(".agengo"))?;
        fs::write(dir.path().join(PATH), "agent: codex\n")?;
        assert_eq!(load(dir.path())?.agent.as_deref(), Some("codex"));
        fs::write(dir.path().join(PATH), "agnet: codex\n")?;
        let error = format!("{:#}", load(dir.path()).unwrap_err());
        assert!(
            error.contains("invalid .agengo/config.yaml") && error.contains("agnet"),
            "{error}"
        );
        Ok(())
    }

    #[test]
    fn set_writes_nested_keys_and_refuses_bad_values() -> Result<()> {
        let dir = tempfile::tempdir()?;
        set(dir.path(), "think.model", Some("opus"))?;
        set(dir.path(), "think.effort", Some("high"))?;
        set(dir.path(), "build.models.codex", Some("small"))?;
        set(dir.path(), "agent", Some("codex"))?;
        let config = load(dir.path())?;
        assert_eq!(config.think.model.as_deref(), Some("opus"));
        assert_eq!(config.think.effort, Some(Effort::High));
        assert_eq!(config.build.models["codex"], "small");
        assert_eq!(config.agent.as_deref(), Some("codex"));
        let before = fs::read_to_string(dir.path().join(PATH))?;
        assert!(set(dir.path(), "think.effort", Some("extreme")).is_err());
        assert!(set(dir.path(), "think.speed", Some("1")).is_err());
        assert_eq!(fs::read_to_string(dir.path().join(PATH))?, before);
        set(dir.path(), "think.effort", None)?;
        assert_eq!(load(dir.path())?.think.effort, None);
        Ok(())
    }

    #[test]
    fn tiers_pick_model_and_effort_per_agent() -> Result<()> {
        let config: Config = serde_yaml_ng::from_str(
            "think: {model: big, effort: high, models: {codex: gpt-big}}\nbuild: {effort: low}\n",
        )?;
        let think = config.pick("review", "claude");
        assert_eq!(
            (think.tier, think.model.as_deref(), think.effort),
            ("think", Some("big"), Some(Effort::High))
        );
        assert_eq!(
            config.pick("plan", "codex").model.as_deref(),
            Some("gpt-big")
        );
        for role in ["plan", "specify", "review", "verify"] {
            assert_eq!(Config::tier_of(role), "think", "{role}");
        }
        let build = config.pick("build", "claude");
        assert_eq!(
            (build.tier, build.model, build.effort),
            ("build", None, Some(Effort::Low))
        );
        assert_eq!(
            config.describe("codex").as_deref(),
            Some("think: gpt-big, effort high ยท build: effort low")
        );
        assert_eq!(Config::default().describe("claude"), None);
        assert_eq!(
            Config::default().pick("build", "claude"),
            Pick {
                tier: "build",
                ..Pick::default()
            }
        );
        // An unknown effort or key is refused, naming it.
        for text in ["think: {effort: extreme}\n", "build: {modle: x}\n"] {
            assert!(serde_yaml_ng::from_str::<Config>(text).is_err(), "{text}");
        }
        Ok(())
    }

    #[test]
    fn setting_the_agent_keeps_other_keys_and_can_clear_it() -> Result<()> {
        let dir = tempfile::tempdir()?;
        set_agent(dir.path(), Some("agy"))?;
        assert_eq!(load(dir.path())?.agent.as_deref(), Some("agy"));
        fs::write(dir.path().join(PATH), "agent: agy\nthink: {effort: low}\n")?;
        set_agent(dir.path(), Some("codex"))?;
        let text = fs::read_to_string(dir.path().join(PATH))?;
        assert!(
            text.contains("agent: codex") && text.contains("effort: low"),
            "{text}"
        );
        let mut value: Value = serde_yaml_ng::from_str(&text)?;
        value.as_mapping_mut().unwrap().remove("think");
        fs::write(dir.path().join(PATH), serde_yaml_ng::to_string(&value)?)?;
        set_agent(dir.path(), None)?;
        assert_eq!(load(dir.path())?, Config::default());
        Ok(())
    }
}