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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Typed view of a validated plan.
//!
//! `contract::validate_plan` checks a plan document and normalizes it to
//! JSON. These types read that normalized form, so the rest of the program
//! gets compile-time field names instead of string keys. Serializing a
//! `Plan` gives back the same JSON, which is what the state database and the
//! agent requests store.

use anyhow::{Context, Result};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::{
    collections::BTreeMap,
    ffi::OsStr,
    path::{Path, PathBuf},
};

/// A command and its arguments, run without a shell.
pub type Argv = Vec<String>;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Plan {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_version: Option<u64>,
    pub goal: String,
    pub tasks: Vec<Task>,
    #[serde(default)]
    pub setup: Vec<Argv>,
    #[serde(default)]
    pub integration_verify: Vec<Argv>,
    pub final_verify: Vec<Argv>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quality: Option<Quality>,
    /// The approved spec this plan implements (see `agengo spec`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spec: Option<SpecRef>,
    /// Choices the planner made that the goal, spec and principles left
    /// open, for the person approving the plan. They do not change the run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assumptions: Vec<Assumption>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Assumption {
    pub text: String,
    pub impact: String,
    pub if_wrong: String,
}

/// The spec file a plan was drafted from, the digest it was approved with,
/// and the user stories the plan covers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SpecRef {
    pub path: String,
    pub digest: String,
    pub stories: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Task {
    pub id: String,
    pub goal: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default)]
    pub depends: Vec<String>,
    pub owns: Vec<String>,
    pub acceptance: Vec<Acceptance>,
    #[serde(default)]
    pub setup: Vec<Argv>,
    pub verify: Vec<Argv>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependency_context: Vec<DependencyContext>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub related_to: Vec<Related>,
}

/// An acceptance criterion as written in the plan: plain text gets the id
/// `AC-<position>`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Acceptance {
    Text(String),
    Item {
        id: String,
        text: String,
        /// Spec requirements (`FR-n`) and success criteria (`SC-n`) this
        /// criterion checks.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        refs: Vec<String>,
    },
}

/// An acceptance criterion with its resolved id.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Criterion {
    pub id: String,
    pub text: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DependencyContext {
    pub task_id: String,
    pub needed_for: String,
    #[serde(default)]
    pub refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Related {
    pub task_id: String,
    pub reason: String,
    #[serde(default)]
    pub refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Quality {
    #[serde(default, deserialize_with = "duplicate_mode")]
    pub python_duplicates: DuplicateMode,
    #[serde(default)]
    pub ignore_paths: Vec<String>,
    #[serde(default)]
    pub checks: Vec<Argv>,
    #[serde(default)]
    pub review: bool,
    /// Have a verifier try to refute each blocking review finding before the
    /// task goes back to the Builder.
    #[serde(default)]
    pub verify_findings: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DuplicateMode {
    Off,
    #[default]
    Warn,
    Block,
}

/// Plans stored by 0.2.x may hold `true` (block) or `false` (off).
fn duplicate_mode<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DuplicateMode, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Stored {
        Legacy(bool),
        Mode(DuplicateMode),
    }
    Ok(match Stored::deserialize(deserializer)? {
        Stored::Legacy(true) => DuplicateMode::Block,
        Stored::Legacy(false) => DuplicateMode::Off,
        Stored::Mode(mode) => mode,
    })
}

impl Plan {
    /// Read a plan normalized by `contract::validate_plan` or stored by an
    /// earlier run.
    pub fn from_value(value: Value) -> Result<Self> {
        serde_json::from_value(value).context("stored plan does not match the plan format")
    }

    pub fn to_value(&self) -> Value {
        serde_json::to_value(self).expect("a plan always serializes to JSON")
    }

    /// The task with this id. The run's task rows mirror the plan, so a
    /// missing id means the state database and the plan disagree.
    pub fn task(&self, id: &str) -> Result<&Task> {
        self.tasks
            .iter()
            .find(|task| task.id == id)
            .with_context(|| format!("task {id} is not in the current plan"))
    }

    /// The quality policy, with defaults when the plan sets none.
    pub fn quality(&self) -> Quality {
        self.quality.clone().unwrap_or_default()
    }

    /// Every command the run will execute on this machine, one line each,
    /// in the order of the phases, so an approver reads exactly what runs.
    /// A line starts with `!` when the command looks risky (see [`risk`]).
    pub fn command_lines(&self) -> Vec<String> {
        let mut lines = Vec::new();
        let mut add = |phase: &str, commands: &[Argv]| {
            for argv in commands {
                let text = argv
                    .iter()
                    .map(|arg| {
                        if arg.is_empty() || arg.contains(char::is_whitespace) {
                            format!("{arg:?}")
                        } else {
                            arg.clone()
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(" ");
                lines.push(match risk(argv) {
                    Some(why) => format!("! {phase}: {text} ({why})"),
                    None => format!("{phase}: {text}"),
                });
            }
        };
        add("setup", &self.setup);
        for task in &self.tasks {
            add(&format!("{} setup", task.id), &task.setup);
            add(&format!("{} verify", task.id), &task.verify);
        }
        add("integration_verify", &self.integration_verify);
        add("final_verify", &self.final_verify);
        if let Some(quality) = &self.quality {
            add("quality check", &quality.checks);
        }
        lines
    }
}

/// What looking up the programs of a plan's commands found.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Preflight {
    /// Problems that make the run pointless: nothing in the plan can supply
    /// the program.
    pub errors: Vec<String>,
    /// Programs that may be missing or may not be what they seem.
    pub warnings: Vec<String>,
}

impl Plan {
    /// Check, before any agent starts, that the programs the plan's commands
    /// name (bare names only; `./script` and `node_modules/.bin/x` may be
    /// created during the run) can be found. This only looks them up and never
    /// runs them, because the plan may not be approved yet. A missing program
    /// is an error when no `setup` command could provide it, a warning when
    /// one might. A program that is a Microsoft Store alias, or a Windows
    /// program reached from WSL2, is a warning.
    pub fn preflight(
        &self,
        base: &Path,
        environment: &crate::platform::Environment,
        find: &dyn Fn(&OsStr, &Path) -> Option<PathBuf>,
    ) -> Preflight {
        let mut uses: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let mut add = |phase: &str, commands: &[Argv]| {
            for argv in commands {
                if let Some(program) = argv.first() {
                    if !program.is_empty() && !program.contains(['/', '\\']) {
                        let phases = uses.entry(program.clone()).or_default();
                        if !phases.iter().any(|known| known == phase) {
                            phases.push(phase.to_owned());
                        }
                    }
                }
            }
        };
        add("setup", &self.setup);
        for task in &self.tasks {
            add(&format!("{} setup", task.id), &task.setup);
            add(&format!("{} verify", task.id), &task.verify);
        }
        add("integration_verify", &self.integration_verify);
        add("final_verify", &self.final_verify);
        if let Some(quality) = &self.quality {
            add("quality check", &quality.checks);
        }
        let has_setup =
            !self.setup.is_empty() || self.tasks.iter().any(|task| !task.setup.is_empty());
        let mut result = Preflight::default();
        for (program, phases) in uses {
            let used = phases.join(", ");
            match find(OsStr::new(&program), base) {
                None if has_setup => result.warnings.push(format!(
                    "`{program}` (used by {used}) is not on PATH; a setup command may provide it, otherwise install it first"
                )),
                None => result.errors.push(format!(
                    "`{program}` (used by {used}) is not on PATH and the plan has no setup command that could provide it; install it, or fix the command in the plan"
                )),
                Some(path) => {
                    let text = path.to_string_lossy().to_ascii_lowercase();
                    if text.contains("\\windowsapps\\") || text.contains("/windowsapps/") {
                        result.warnings.push(format!(
                            "`{program}` (used by {used}) resolves to {}, a Microsoft Store alias that starts the Store instead of a program; install the real one and put it before WindowsApps in PATH",
                            path.display()
                        ));
                    } else if crate::platform::is_windows_program_in_wsl(environment, &path) {
                        result.warnings.push(format!(
                            "`{program}` (used by {used}) resolves to {}, a Windows program run through WSL2; install the Linux one inside WSL and put it first in PATH",
                            path.display()
                        ));
                    }
                }
            }
        }
        result
    }
}

/// Why a plan command deserves a closer look before approval, if it does.
/// This is a reading aid, not a security boundary: a command that passes can
/// still do harm, and plan commands are not sandboxed.
pub fn risk(argv: &[String]) -> Option<&'static str> {
    let program = argv.first()?;
    let name = program
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(program)
        .trim_end_matches(".exe")
        .to_ascii_lowercase();
    match name.as_str() {
        "sudo" | "su" | "doas" => return Some("runs with elevated rights"),
        "curl" | "wget" | "nc" | "ncat" | "ssh" | "scp" | "ftp" => {
            return Some("talks to the network");
        }
        "sh" | "bash" | "zsh" | "dash" | "fish" | "cmd" | "powershell" | "pwsh"
            if argv.iter().skip(1).any(|arg| {
                matches!(arg.to_ascii_lowercase().as_str(), "-c" | "/c" | "-command")
            }) =>
        {
            return Some("runs a shell string");
        }
        "rm" | "rmdir" | "del" | "mv" | "chmod" | "chown"
            if argv
                .iter()
                .skip(1)
                .any(|arg| !arg.starts_with('-') && outside(arg)) =>
        {
            return Some("changes files outside the worktree");
        }
        _ => {}
    }
    if argv.iter().skip(1).any(|arg| {
        let arg = arg.to_ascii_lowercase();
        arg.contains("curl ")
            || arg.contains("wget ")
            || arg.contains("| sh")
            || arg.contains("|sh")
    }) {
        return Some("pipes a download into a shell");
    }
    None
}

/// An absolute, home-relative or parent-relative path.
fn outside(path: &str) -> bool {
    path.starts_with('/')
        || path.starts_with('~')
        || path.split(['/', '\\']).any(|part| part == "..")
}

impl Task {
    pub fn title(&self) -> &str {
        self.title.as_deref().unwrap_or(&self.goal)
    }

    pub fn criteria(&self) -> Vec<Criterion> {
        self.acceptance
            .iter()
            .enumerate()
            .map(|(index, item)| match item {
                Acceptance::Text(text) => Criterion {
                    id: format!("AC-{}", index + 1),
                    text: text.clone(),
                    refs: Vec::new(),
                },
                Acceptance::Item { id, text, refs } => Criterion {
                    id: id.clone(),
                    text: text.clone(),
                    refs: refs.clone(),
                },
            })
            .collect()
    }

    pub fn depends_on(&self, id: &str) -> bool {
        self.depends.iter().any(|dep| dep == id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contract::validate_plan;
    use serde_json::json;

    fn full_plan() -> Value {
        json!({
            "schema_version": 1,
            "goal": "Ship",
            "setup": [["npm", "ci"]],
            "integration_verify": [["make", "check"]],
            "final_verify": [["make", "test"]],
            "quality": {"python_duplicates": true, "ignore_paths": ["vendor"]},
            "tasks": [
                {"id": "a", "goal": "Build A", "title": "A", "owns": ["src/a"],
                 "acceptance": ["Works", {"id": "AC-X", "text": "Fast"}],
                 "setup": [["true"]], "verify": [["test", "-d", "src/a"]]},
                {"id": "b", "goal": "Build B", "owns": ["src/b"], "depends": ["a"],
                 "acceptance": ["Works"], "verify": [["true"]],
                 "dependency_context": [{"task_id": "a", "needed_for": "API", "refs": ["src/a/api.rs"]}]},
                {"id": "c", "goal": "Build C", "owns": ["src/c"], "acceptance": ["Works"],
                 "verify": [["true"]], "related_to": [{"task_id": "a", "reason": "Same style"}]}
            ]
        })
    }

    #[test]
    fn typed_plan_round_trips_the_normalized_json() -> Result<()> {
        for raw in [
            full_plan(),
            json!({"goal": "Small", "final_verify": [["true"]], "tasks": [
                {"id": "only", "goal": "One", "owns": ["x"], "acceptance": ["Done"], "verify": [["true"]]}
            ]}),
        ] {
            let normalized = validate_plan(raw)?;
            let plan = Plan::from_value(normalized.clone())?;
            assert_eq!(plan.to_value(), normalized);
        }
        Ok(())
    }

    #[test]
    fn criteria_quality_and_lookups() -> Result<()> {
        let plan = Plan::from_value(validate_plan(full_plan())?)?;
        let a = plan.task("a")?;
        assert_eq!(a.title(), "A");
        assert_eq!(plan.task("b")?.title(), "Build B");
        assert!(plan.task("missing").is_err());
        assert_eq!(
            a.criteria(),
            vec![
                Criterion {
                    id: "AC-1".into(),
                    text: "Works".into(),
                    refs: Vec::new(),
                },
                Criterion {
                    id: "AC-X".into(),
                    text: "Fast".into(),
                    refs: Vec::new(),
                },
            ]
        );
        assert!(plan.task("b")?.depends_on("a"));
        let quality = plan.quality();
        assert_eq!(quality.python_duplicates, DuplicateMode::Block);
        assert_eq!(quality.ignore_paths, ["vendor"]);
        assert_eq!(
            Plan::from_value(json!({"goal":"g","final_verify":[["true"]],"tasks":[]}))?.quality(),
            Quality::default()
        );
        Ok(())
    }

    #[test]
    fn command_lines_list_every_command_and_flag_risky_ones() -> Result<()> {
        let plan = Plan::from_value(json!({"goal":"g","setup":[["npm","ci"]],
            "final_verify":[["sh","-c","curl x | sh"],["cargo","test"]],
            "tasks":[{"id":"a","goal":"A","owns":["x"],"acceptance":["ok"],
                "verify":[["rm","-rf","/tmp/x"],["echo","two words"]]}]}))?;
        assert_eq!(
            plan.command_lines(),
            [
                "setup: npm ci",
                "! a verify: rm -rf /tmp/x (changes files outside the worktree)",
                "a verify: echo \"two words\"",
                "! final_verify: sh -c \"curl x | sh\" (runs a shell string)",
                "final_verify: cargo test",
            ]
        );
        assert_eq!(risk(&["rm".into(), "-rf".into(), "build".into()]), None);
        assert_eq!(
            risk(&["sudo".into(), "make".into()]),
            Some("runs with elevated rights")
        );
        Ok(())
    }

    #[test]
    fn preflight_finds_missing_programs_and_misleading_ones() -> Result<()> {
        use crate::platform::Environment;
        let plan = |setup: Value| {
            Plan::from_value(json!({"goal":"g","setup":setup,
                "final_verify":[["python","-m","pytest"],["./run-checks.sh"]],
                "tasks":[{"id":"a","goal":"A","owns":["x"],"acceptance":["ok"],
                    "verify":[["python","-c","1"],["cargo","test"]]}]}))
        };
        let known = |program: &OsStr, _: &Path| {
            let name = program.to_string_lossy();
            match name.as_ref() {
                "cargo" => Some(PathBuf::from("/usr/bin/cargo")),
                _ => None,
            }
        };
        let base = Path::new("/repo");
        // Nothing can install python, so the run would fail after spending tokens.
        let found = plan(json!([]))?.preflight(base, &Environment::Linux, &known);
        assert_eq!(found.errors.len(), 1, "{found:?}");
        assert!(
            found.errors[0].contains("`python`")
                && found.errors[0].contains("a verify, final_verify")
        );
        // `./run-checks.sh` is not looked up: the run may create it.
        assert!(!found.errors[0].contains("run-checks"));
        // With a setup command the program might appear, so it only warns.
        let found = plan(json!([["pip", "install", "pytest"]]))?.preflight(
            base,
            &Environment::Linux,
            &known,
        );
        assert!(found.errors.is_empty(), "{found:?}");
        assert!(found.warnings.iter().any(|w| w.contains("`python`")));
        // The Microsoft Store alias and a Windows program in WSL2.
        let alias = |_: &OsStr, _: &Path| {
            Some(PathBuf::from(
                "C:/Users/me/AppData/Local/Microsoft/WindowsApps/python.exe",
            ))
        };
        let found = plan(json!([]))?.preflight(base, &Environment::Windows, &alias);
        assert!(found.errors.is_empty());
        assert!(
            found
                .warnings
                .iter()
                .any(|w| w.contains("Microsoft Store alias")),
            "{found:?}"
        );
        let interop = |_: &OsStr, _: &Path| Some(PathBuf::from("/mnt/c/Python/python.exe"));
        let found = plan(json!([]))?.preflight(base, &Environment::Wsl2(None), &interop);
        assert!(
            found
                .warnings
                .iter()
                .any(|w| w.contains("through WSL2") || w.contains("run through WSL2")),
            "{found:?}"
        );
        Ok(())
    }

    #[test]
    fn stored_legacy_duplicate_flags_are_read() -> Result<()> {
        let quality: Quality = serde_json::from_value(json!({"python_duplicates": false}))?;
        assert_eq!(quality.python_duplicates, DuplicateMode::Off);
        assert!(serde_json::from_value::<Quality>(json!({"python_duplicates": "maybe"})).is_err());
        Ok(())
    }
}