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
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use crate::plan::Plan;
use anyhow::{anyhow, bail, Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Component, Path},
};

pub const STATE_SQL: &str = include_str!("../specs/state.sql");
const ROLES: &str = include_str!("../specs/roles.yaml");
const REQUIRED_ROLES: [&str; 3] = ["build", "plan", "review"];
const OPTIONAL_ROLES: [&str; 2] = ["specify", "verify"];

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct Catalog {
    schema_version: u32,
    roles: BTreeMap<String, Role>,
}
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct Role {
    instructions: String,
    output_schema: String,
    purpose: String,
    file_access: String,
    #[serde(default)]
    handoff_prompts: BTreeMap<String, String>,
    integrated_prompt: Option<String>,
}

pub fn builtin_asset(name: &str) -> Result<String> {
    Ok(match name {
        "roles.yaml" => ROLES,
        "planner-output.schema.json" => {
            include_str!("../specs/planner-output.schema.json")
        }
        "outcome.schema.json" => include_str!("../specs/outcome.schema.json"),
        "prompts/plan.md" => include_str!("../specs/prompts/plan.md"),
        "prompts/build.md" => include_str!("../specs/prompts/build.md"),
        "prompts/review.md" => include_str!("../specs/prompts/review.md"),
        "verification.schema.json" => include_str!("../specs/verification.schema.json"),
        "prompts/verify.md" => include_str!("../specs/prompts/verify.md"),
        "specify-output.schema.json" => include_str!("../specs/specify-output.schema.json"),
        "prompts/specify.md" => include_str!("../specs/prompts/specify.md"),
        "prompts/build-worktree.md" => {
            include_str!("../specs/prompts/build-worktree.md")
        }
        "prompts/build-commit.md" => include_str!("../specs/prompts/build-commit.md"),
        "prompts/review-integrated.md" => {
            include_str!("../specs/prompts/review-integrated.md")
        }
        _ => bail!("unknown built-in asset: {name}"),
    }
    .into())
}

pub fn profile(path: Option<&Path>) -> Result<Value> {
    let source = match path {
        Some(p) => fs::read_to_string(p)?,
        None => ROLES.into(),
    };
    let catalog: Catalog = serde_yaml_ng::from_str(&source).context("invalid roles YAML")?;
    // `specify` and `verify` are optional so roles files written before they
    // existed still load; they get the built-in roles.
    let names: BTreeSet<&str> = catalog.roles.keys().map(String::as_str).collect();
    if catalog.schema_version != 1
        || !REQUIRED_ROLES.iter().all(|name| names.contains(name))
        || names
            .iter()
            .any(|name| !REQUIRED_ROLES.contains(name) && !OPTIONAL_ROLES.contains(name))
    {
        bail!("roles YAML needs schema_version 1 and build, plan and review (specify and verify are optional)");
    }
    let asset = |name: &str| -> Result<String> {
        scope_path(name)?;
        match path {
            Some(p) => fs::read_to_string(p.parent().unwrap_or(Path::new(".")).join(name))
                .with_context(|| format!("cannot read role asset {name}")),
            None => builtin_asset(name),
        }
    };
    let mut result = serde_json::Map::new();
    for (name, role) in catalog.roles {
        let expected_access = if name == "build" {
            "assigned_scope"
        } else {
            "read_only"
        };
        if role.file_access != expected_access || role.purpose.trim().is_empty() {
            bail!("invalid access or purpose for role {name}");
        }
        // Wire validation keeps the built-in contract even when prompts are edited.
        let expected_schema = match name.as_str() {
            "plan" => "planner-output.schema.json",
            "verify" => "verification.schema.json",
            "specify" => "specify-output.schema.json",
            _ => "outcome.schema.json",
        };
        if role.output_schema != expected_schema
            && !(name == "plan" && role.output_schema == "plan.schema.json")
        {
            bail!("role {name} must use {expected_schema}");
        }
        if name == "build"
            && role
                .handoff_prompts
                .keys()
                .map(String::as_str)
                .ne(["commit", "worktree"])
        {
            bail!("build role needs commit and worktree handoff prompts");
        }
        let handoff = role
            .handoff_prompts
            .iter()
            .map(|(key, value)| Ok((key.clone(), asset(value)?)))
            .collect::<Result<BTreeMap<_, _>>>()?;
        let integrated = role.integrated_prompt.as_deref().map(asset).transpose()?;
        result.insert(name, json!({
            "instructions": asset(&role.instructions)?, "schema": builtin_asset(expected_schema)?,
            "handoff_prompts": handoff, "integrated_prompt": integrated,
            "purpose": role.purpose, "file_access": role.file_access,
        }));
    }
    let builtin: Catalog = serde_yaml_ng::from_str(ROLES)?;
    for name in OPTIONAL_ROLES {
        if result.contains_key(name) {
            continue;
        }
        let role = &builtin.roles[name];
        result.insert(
            name.into(),
            json!({
                "instructions": builtin_asset(&role.instructions)?,
                "schema": builtin_asset(&role.output_schema)?,
                "handoff_prompts": {}, "integrated_prompt": null,
                "purpose": role.purpose, "file_access": role.file_access,
            }),
        );
    }
    Ok(json!({"schema_version": 1, "roles": result}))
}

/// "1 task", "2 tasks": English count with a regular plural.
pub fn count(n: usize, noun: &str) -> String {
    format!("{n} {noun}{}", if n == 1 { "" } else { "s" })
}

pub fn string_or_empty(value: &Value) -> &str {
    value.as_str().unwrap_or("")
}
pub fn array_or_empty(value: &Value) -> &[Value] {
    value.as_array().map(Vec::as_slice).unwrap_or(&[])
}
pub fn text<'a>(value: &'a Value, label: &str) -> Result<&'a str> {
    value
        .as_str()
        .filter(|s| !s.trim().is_empty())
        .ok_or_else(|| anyhow!("{label} must be a nonempty string"))
}
pub fn identifier(value: &str, label: &str) -> Result<()> {
    if value.is_empty()
        || value.len() > 64
        || !value.as_bytes()[0].is_ascii_alphanumeric()
        || !value
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
    {
        bail!("{label} must contain 1–64 letters, digits, underscores or hyphens");
    }
    Ok(())
}
pub fn scope_path(path: &str) -> Result<()> {
    let normalized = Path::new(path)
        .components()
        .map(|part| match part {
            Component::Normal(value) if value != ".git" => value.to_str(),
            _ => None,
        })
        .collect::<Option<Vec<_>>>();
    if path.is_empty()
        || path.contains(['\\', '\0'])
        || normalized.map(|p| p.join("/")).as_deref() != Some(path)
    {
        bail!("invalid repository-relative path: {path:?}");
    }
    Ok(())
}
/// Whether `path` equals one of `scopes` or lies below one of them.
pub fn owns<S: AsRef<str>>(path: &str, scopes: &[S]) -> bool {
    scopes.iter().any(|scope| {
        let scope = scope.as_ref();
        path == scope
            || path
                .strip_prefix(scope)
                .is_some_and(|tail| tail.starts_with('/'))
    })
}
pub fn overlaps<S: AsRef<str>>(left: &[S], right: &[S]) -> bool {
    left.iter().any(|path| owns(path.as_ref(), right))
        || right.iter().any(|path| owns(path.as_ref(), left))
}

fn criteria(task: &Value) -> Result<Vec<Value>> {
    let mut ids = BTreeSet::new();
    array_or_empty(&task["acceptance"])
        .iter()
        .enumerate()
        .map(|(index, item)| {
            let (id, message) = if item.is_object() {
                fields(item, "acceptance item", &["id", "text", "refs"])?;
                let id = text(&item["id"], "acceptance id")?;
                identifier(id, "acceptance id")?;
                (id.into(), text(&item["text"], "acceptance text")?)
            } else {
                (format!("AC-{}", index + 1), text(item, "acceptance text")?)
            };
            if !ids.insert(id.clone()) {
                bail!("duplicate acceptance id {id}");
            }
            let mut criterion = json!({"id": id, "text": message});
            let none = json!([]);
            let refs = strings(item.get("refs").unwrap_or(&none), "acceptance refs", false)?;
            for reference in array_or_empty(&refs) {
                let reference = string_or_empty(reference);
                if !spec_reference(reference) {
                    bail!("acceptance ref {reference:?} must name a spec requirement (FR-1) or success criterion (SC-1)");
                }
            }
            if !array_or_empty(&refs).is_empty() {
                criterion["refs"] = refs;
            }
            Ok(criterion)
        })
        .collect()
}

/// `FR-n` or `SC-n`, the spec items an acceptance criterion can check.
fn spec_reference(id: &str) -> bool {
    ["FR-", "SC-"].iter().any(|prefix| {
        id.strip_prefix(prefix).is_some_and(|digits| {
            (1..=4).contains(&digits.len()) && digits.bytes().all(|c| c.is_ascii_digit())
        })
    })
}

pub fn fields(value: &Value, label: &str, allowed: &[&str]) -> Result<()> {
    let object = value
        .as_object()
        .with_context(|| format!("{label} must be an object"))?;
    if let Some(key) = object.keys().find(|key| !allowed.contains(&key.as_str())) {
        bail!("unknown field {key:?} in {label}");
    }
    Ok(())
}

fn strings(value: &Value, label: &str, required: bool) -> Result<Value> {
    let values = value
        .as_array()
        .filter(|v| !required || !v.is_empty())
        .ok_or_else(|| {
            anyhow!(
                "{label} must be a list{} ",
                if required {
                    " with at least one entry"
                } else {
                    ""
                }
            )
        })?;
    for item in values {
        text(item, label)?;
    }
    Ok(value.clone())
}
fn commands(value: &Value, label: &str, required: bool) -> Result<Value> {
    let values = value.as_array().ok_or_else(|| {
        anyhow!(
            "{label} must be a list of commands, each an argv list such as [[\"cargo\", \"test\"]]"
        )
    })?;
    if required && values.is_empty() {
        bail!("{label} is missing or empty; add at least one command, such as [[\"cargo\", \"test\"]]");
    }
    for item in values {
        strings(item, label, true)?;
    }
    Ok(value.clone())
}

fn optional_list<'a>(object: &'a Value, key: &str, empty: &'a Value) -> &'a Value {
    object.get(key).unwrap_or(empty)
}

pub fn quality(plan: &Value) -> Result<Value> {
    let mut output = json!({"python_duplicates": "warn", "ignore_paths": [], "checks": [], "review": false,
            "verify_findings": false});
    if let Some(policy) = plan.get("quality") {
        let fields = policy
            .as_object()
            .ok_or_else(|| anyhow!("quality must be an object"))?;
        for (key, value) in fields {
            output[key] = match key.as_str() {
                // true/false are kept for plans written for 0.2.x, where true blocked.
                "python_duplicates" => match value {
                    Value::Bool(true) => json!("block"),
                    Value::Bool(false) => json!("off"),
                    Value::String(mode) if matches!(mode.as_str(), "off" | "warn" | "block") => {
                        value.clone()
                    }
                    _ => bail!("quality.python_duplicates must be off, warn or block"),
                },
                "review" | "verify_findings" if value.is_boolean() => value.clone(),
                "ignore_paths" => {
                    let paths = strings(value, key, false)?;
                    for path in array_or_empty(&paths) {
                        scope_path(string_or_empty(path))?;
                    }
                    paths
                }
                "checks" => commands(value, key, false)?,
                _ => bail!("invalid quality option {key}"),
            };
        }
    }
    Ok(output)
}

pub fn validate_version(value: &Value) -> Result<()> {
    if value
        .get("schema_version")
        .is_some_and(|version| version.as_u64() != Some(1))
    {
        bail!("unsupported plan schema_version; expected 1");
    }
    Ok(())
}

pub fn validate_plan(raw: Value) -> Result<Value> {
    fields(
        &raw,
        "plan",
        &[
            "schema_version",
            "goal",
            "tasks",
            "setup",
            "integration_verify",
            "final_verify",
            "questions",
            "quality",
            "spec",
            "assumptions",
        ],
    )?;
    validate_version(&raw)?;
    let empty = json!([]);
    if !array_or_empty(&strings(
        optional_list(&raw, "questions", &empty),
        "questions",
        false,
    )?)
    .is_empty()
    {
        bail!("the draft has unresolved questions; revise it before running");
    }
    let tasks = raw["tasks"]
        .as_array()
        .filter(|items| !items.is_empty())
        .ok_or_else(|| anyhow!("tasks must be a nonempty list"))?;
    let mut known = BTreeSet::new();
    for task in tasks {
        fields(
            task,
            "task",
            &[
                "id",
                "goal",
                "title",
                "depends",
                "owns",
                "acceptance",
                "setup",
                "verify",
                "dependency_context",
                "related_to",
            ],
        )?;
        let id = text(&task["id"], "task id")?;
        identifier(id, "task id")?;
        if !known.insert(id) {
            bail!("duplicate task id {id}");
        }
    }
    let mut normalized = Vec::new();
    for task in tasks {
        let id = string_or_empty(&task["id"]);
        let owned = strings(&task["owns"], "owns", true)?;
        for path in array_or_empty(&owned) {
            scope_path(string_or_empty(path))?;
        }
        let depends = strings(optional_list(task, "depends", &empty), "depends", false)?;
        for dep in array_or_empty(&depends) {
            if !known.contains(string_or_empty(dep)) {
                bail!("{id} has unknown dependencies: {}", string_or_empty(dep));
            }
        }
        if !task["acceptance"].is_array() {
            bail!("{id}.acceptance must be a nonempty list");
        }
        let acceptance = criteria(task)?;
        if acceptance.is_empty() {
            bail!("{id}.acceptance must be a nonempty list");
        }
        let acceptance: Vec<Value> = array_or_empty(&task["acceptance"])
            .iter()
            .zip(acceptance)
            .map(|(original, item)| {
                if original.is_object() {
                    item
                } else {
                    item["text"].clone()
                }
            })
            .collect();
        let mut output = json!({
            "id": id, "goal": text(&task["goal"], "task goal")?, "depends": depends, "owns": owned,
            "acceptance": acceptance, "setup": commands(optional_list(task, "setup", &empty), "setup", false)?,
            "verify": commands(&task["verify"], "verify", true)?,
        });
        if let Some(title) = task.get("title") {
            output["title"] = json!(text(title, "title")?);
        }
        for (field, explanation) in [
            ("dependency_context", "needed_for"),
            ("related_to", "reason"),
        ] {
            let Some(value) = task.get(field) else {
                continue;
            };
            let relations = value
                .as_array()
                .ok_or_else(|| anyhow!("{id}.{field} must be a list"))?;
            let mut seen = BTreeSet::new();
            let mut details = Vec::new();
            for relation in relations {
                fields(
                    relation,
                    &format!("{id}.{field}"),
                    &["task_id", explanation, "refs"],
                )?;
                let key = text(&relation["task_id"], field)?;
                let is_dep = array_or_empty(&depends)
                    .iter()
                    .any(|dep| string_or_empty(dep) == key);
                if !known.contains(key)
                    || key == id
                    || !seen.insert(key)
                    || is_dep != (field == "dependency_context")
                {
                    bail!("{id}.{field} has invalid relation to {key}");
                }
                let refs = strings(optional_list(relation, "refs", &empty), "refs", false)?;
                for path in array_or_empty(&refs) {
                    scope_path(string_or_empty(path))?;
                }
                details.push(json!({"task_id": key, (explanation): text(&relation[explanation], explanation)?, "refs": refs}));
            }
            if !details.is_empty() {
                output[field] = json!(details);
            }
        }
        normalized.push(output);
    }
    let mut unresolved: BTreeSet<_> = known;
    while !unresolved.is_empty() {
        let ready: Vec<_> = normalized
            .iter()
            .filter(|task| {
                unresolved.contains(string_or_empty(&task["id"]))
                    && array_or_empty(&task["depends"])
                        .iter()
                        .all(|dep| !unresolved.contains(string_or_empty(dep)))
            })
            .map(|task| string_or_empty(&task["id"]))
            .collect();
        if ready.is_empty() {
            bail!("dependency cycle affects: {unresolved:?}");
        }
        for id in ready {
            unresolved.remove(id);
        }
    }
    let mut result = json!({
        "goal": text(&raw["goal"], "goal")?, "tasks": normalized,
        "setup": commands(optional_list(&raw, "setup", &empty), "setup", false)?,
        "integration_verify": commands(optional_list(&raw, "integration_verify", &empty), "integration_verify", false)?,
        "final_verify": commands(&raw["final_verify"], "final_verify", true)?,
    });
    if raw.get("quality").is_some() {
        result["quality"] = quality(&raw)?;
    }
    if raw.get("schema_version").is_some() {
        result["schema_version"] = json!(1);
    }
    let referenced = normalized.iter().any(|task| {
        array_or_empty(&task["acceptance"])
            .iter()
            .any(|item| item.get("refs").is_some())
    });
    let assumptions = assumptions(optional_list(&raw, "assumptions", &empty))?;
    if !assumptions.is_empty() {
        result["assumptions"] = json!(assumptions);
    }
    match raw.get("spec") {
        Some(spec) => result["spec"] = spec_ref(spec)?,
        None if referenced => bail!("acceptance refs need the plan's spec field"),
        None => {}
    }
    Ok(result)
}

/// The planner's assumptions: what it chose where the goal, spec and
/// principles left a choice open, how much a wrong guess would cost, and
/// what would change.
fn assumptions(value: &Value) -> Result<Vec<Value>> {
    let items = value
        .as_array()
        .ok_or_else(|| anyhow!("assumptions must be a list"))?;
    items
        .iter()
        .map(|item| {
            fields(item, "assumption", &["text", "impact", "if_wrong"])?;
            let impact = text(&item["impact"], "assumption impact")?;
            if !["high", "medium", "low"].contains(&impact) {
                bail!("assumption impact must be high, medium or low");
            }
            Ok(
                json!({"text": text(&item["text"], "assumption text")?, "impact": impact,
                "if_wrong": text(&item["if_wrong"], "assumption if_wrong")?}),
            )
        })
        .collect()
}

/// The plan's `spec` field: which spec file, its approved digest, and the
/// stories the plan covers. `agengo::spec::coverage` checks it against the
/// file.
fn spec_ref(spec: &Value) -> Result<Value> {
    fields(spec, "spec", &["path", "digest", "stories"])?;
    let digest = text(&spec["digest"], "spec digest")?;
    if !digest.starts_with("sha256:") {
        bail!("spec digest must start with sha256:");
    }
    let stories = strings(&spec["stories"], "spec stories", true)?;
    Ok(json!({"path": text(&spec["path"], "spec path")?, "digest": digest, "stories": stories}))
}

pub fn load_plan(path: &Path) -> Result<Plan> {
    let input =
        fs::read_to_string(path).with_context(|| format!("cannot read plan {}", path.display()))?;
    let raw = match path.extension().and_then(|value| value.to_str()) {
        Some("yaml" | "yml") => serde_yaml_ng::from_str(&input).context("invalid YAML plan")?,
        _ => serde_json::from_str(&input).context("invalid JSON plan")?,
    };
    Plan::from_value(validate_plan(raw)?)
}

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

    #[test]
    fn duplicate_mode_defaults_to_warn_and_maps_legacy_booleans() -> Result<()> {
        assert_eq!(quality(&json!({}))?["python_duplicates"], "warn");
        for (input, expected) in [
            (json!(true), "block"),
            (json!(false), "off"),
            (json!("warn"), "warn"),
            (json!("block"), "block"),
            (json!("off"), "off"),
        ] {
            let policy = quality(&json!({"quality":{"python_duplicates":input}}))?;
            assert_eq!(policy["python_duplicates"], expected);
        }
        assert!(quality(&json!({"quality":{"python_duplicates":"maybe"}})).is_err());
        assert!(quality(&json!({"quality":{"unknown":true}})).is_err());
        Ok(())
    }

    #[test]
    fn scope_paths_stay_inside_the_repository() {
        for good in ["src", "src/a.txt", "docs/guide.md"] {
            assert!(scope_path(good).is_ok(), "{good}");
        }
        for bad in [
            "",
            "/etc",
            "../x",
            "a/../b",
            "./a",
            ".git",
            "sub/.git/config",
            "a\\b",
            "a//b",
        ] {
            assert!(scope_path(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn ownership_uses_path_boundaries() {
        let scope = ["src/app"];
        assert!(owns("src/app", &scope));
        assert!(owns("src/app/main.rs", &scope));
        assert!(!owns("src/application.rs", &scope));
        assert!(overlaps(&["src"], &["src/a.txt"]));
        assert!(!overlaps(&["src/a"], &["src/b"]));
    }

    #[test]
    fn build_prompt_carries_the_fix_procedure() -> Result<()> {
        assert!(builtin_asset("prompts/build.md")?.contains("last_failure"));
        let profile = profile(None)?;
        let instructions = string_or_empty(&profile["roles"]["build"]["instructions"]);
        assert!(instructions.contains("context.last_failure"));
        Ok(())
    }
}