agengo 0.5.4

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
use super::*;

fn question(category: &str, impact: &str) -> Value {
    json!({"category": category, "impact": impact, "question": "Who?", "why": "Scope",
        "options": [{"key": "A", "label": "Owner", "implication": "Smaller"},
                    {"key": "B", "label": "Staff", "implication": "Logins"}],
        "recommended": "A"})
}

fn ready_body() -> Value {
    json!({"problem": "Orders get lost", "actors": ["owner"],
        "stories": [{"id": "US-1", "priority": "P1", "title": "Record a sale",
            "scenarios": ["Given stock, When I sell, Then stock drops"]}],
        "requirements": [{"id": "FR-1", "story": "US-1", "text": "Record a sale"}],
        "success_criteria": [{"id": "SC-1", "text": "A sale takes under 30 seconds"}],
        "out_of_scope": ["Online payment"], "constraints": [], "assumptions": [],
        "feasibility": [], "candidate_questions": []})
}

#[test]
fn civil_time_handles_epoch_and_leap_days() {
    assert_eq!(civil(0), "1970-01-01T00:00:00Z");
    assert_eq!(civil(951_782_400 + 3_661), "2000-02-29T01:01:01Z");
}

#[test]
fn digest_ignores_key_order_and_approval_but_not_content() {
    let left = json!({"a": 1, "b": {"c": [1, 2]}, "approved": null});
    let right = json!({"b": {"c": [1, 2]}, "approved": {"digest": "x"}, "a": 1});
    assert_eq!(digest(&left), digest(&right));
    assert_ne!(digest(&left), digest(&json!({"a": 2, "b": {"c": [1, 2]}})));
    assert!(digest(&left).starts_with("sha256:") && digest(&left).len() == 71);
}

#[test]
fn revise_keeps_the_five_most_important_valid_questions() -> Result<()> {
    let mut spec = empty("idea");
    spec["questions_issued"] = json!(2);
    let mut reply = ready_body();
    let mut tech = question("scope", "high");
    tech["category"] = json!("tech");
    reply["candidate_questions"] = json!([
        question("terminology", "low"),
        question("data", "medium"),
        tech,
        question("quality", "high"),
        question("flow", "medium"),
        question("scope", "high"),
        question("actors", "high"),
    ]);
    revise(&mut spec, &reply, false)?;
    let kept: Vec<_> = array_or_empty(&spec["questions"])
        .iter()
        .map(|q| {
            format!(
                "{}:{}",
                string_or_empty(&q["id"]),
                string_or_empty(&q["category"])
            )
        })
        .collect();
    assert_eq!(
        kept,
        [
            "Q-3:scope",
            "Q-4:actors",
            "Q-5:quality",
            "Q-6:flow",
            "Q-7:data"
        ]
    );
    assert_eq!(spec["questions_issued"], 7);
    validate(&spec)?;
    revise(&mut spec, &reply, true)?;
    assert_eq!(spec["questions"], json!([]));

    // The depth sets how many are kept; six of the seven are valid.
    for (depth, kept) in [("quick", 3), ("deep", 6)] {
        let mut spec = empty("idea");
        spec["depth"] = json!(depth);
        revise(&mut spec, &reply, false)?;
        assert_eq!(array_or_empty(&spec["questions"]).len(), kept, "{depth}");
        validate(&spec)?;
    }
    Ok(())
}

#[test]
fn question_rules_reject_unusable_questions() {
    assert_eq!(question_problem(&question("scope", "high"), false), None);
    let mut single = question("scope", "high");
    single["options"].as_array_mut().unwrap().pop();
    assert!(question_problem(&single, false).unwrap().contains("2 to 4"));
    let mut stray = question("scope", "high");
    stray["recommended"] = json!("C");
    assert!(question_problem(&stray, false).is_some());
    let mut yes = question("scope", "high");
    yes["options"][1]["key"] = json!("yes");
    assert!(question_problem(&yes, false).is_some());
}

#[test]
fn answers_record_their_source() -> Result<()> {
    let mut spec = empty("idea");
    spec["rounds"] = json!(1);
    spec["questions_issued"] = json!(3);
    spec["questions"] = json!([1, 2, 3]
        .iter()
        .map(|n| {
            let mut q = question("scope", "high");
            q["id"] = json!(format!("Q-{n}"));
            q
        })
        .collect::<Vec<_>>());
    let records = apply_answers(&mut spec, &["Q-1=b".into(), "Q-2 = yes".into()], false)?;
    assert_eq!(records[0]["answer"], "Staff");
    assert_eq!(records[0]["source"], "option");
    assert_eq!(records[1]["answer"], "Owner");
    assert_eq!(records[1]["source"], "recommended");
    assert!(apply_answers(&mut spec.clone(), &["Q-1=A".into()], false).is_err());
    assert!(apply_answers(&mut spec.clone(), &["Q-3".into()], false).is_err());
    let records = apply_answers(&mut spec, &["Q-3=Only weekends".into()], false)?;
    assert_eq!(records[0]["source"], "free");
    assert_eq!(spec["questions"], json!([]));
    assert_eq!(array_or_empty(&spec["clarifications"]).len(), 3);
    Ok(())
}

#[test]
fn readiness_names_each_missing_part() -> Result<()> {
    let mut spec = empty("idea");
    // R2, R5, R6 and R7; R3 and R4 need stories to apply.
    assert_eq!(readiness(&spec).len(), 4);
    revise(&mut spec, &ready_body(), true)?;
    assert_eq!(readiness(&spec), Vec::<String>::new());
    spec["out_of_scope"] = json!([]);
    spec["questions"] = json!([{"id": "Q-1", "impact": "high"}]);
    let failures = readiness(&spec);
    assert!(failures[0].starts_with("R1") && failures[1].starts_with("R6"));
    Ok(())
}

/// An approved spec with P1 story US-1 (FR-1, FR-2) and P2 story US-2
/// (FR-3), written to `directory/spec.yaml`.
fn approved_spec(directory: &Path) -> Result<Value> {
    let mut spec = empty("idea");
    let mut body = ready_body();
    body["stories"] = json!([
        {"id": "US-1", "priority": "P1", "title": "Sell", "scenarios": ["Given, When, Then"]},
        {"id": "US-2", "priority": "P2", "title": "Report", "scenarios": ["Given, When, Then"]}]);
    body["requirements"] = json!([
        {"id": "FR-1", "story": "US-1", "text": "Record"},
        {"id": "FR-2", "story": "US-1", "text": "Stock"},
        {"id": "FR-3", "story": "US-2", "text": "Totals"}]);
    revise(&mut spec, &body, true)?;
    spec["approved"] = json!({"digest": digest(&spec), "at": "now"});
    save(&directory.join("spec.yaml"), &spec)?;
    Ok(spec)
}

fn traced_plan(spec: &Value, refs: &[&[&str]]) -> Result<Plan> {
    let acceptance: Vec<Value> = refs
        .iter()
        .enumerate()
        .map(|(index, refs)| json!({"id": format!("AC-{}", index + 1), "text": "Check", "refs": refs}))
        .collect();
    Plan::from_value(contract::validate_plan(json!({
        "goal": "g", "final_verify": [["true"]],
        "spec": {"path": "spec.yaml", "digest": spec["approved"]["digest"], "stories": ["US-1"]},
        "tasks": [{"id": "a", "goal": "A", "owns": ["a"], "acceptance": acceptance, "verify": [["true"]]}],
    }))?)
}

#[test]
fn principles_are_read_only_once_filled_in() -> Result<()> {
    let root = tempfile::tempdir()?;
    assert_eq!(principles(root.path())?, None);
    let path = root.path().join(PRINCIPLES_PATH);
    fs::create_dir_all(path.parent().unwrap())?;
    fs::write(&path, include_str!("../../specs/principles-template.md"))?;
    assert_eq!(principles(root.path())?, None, "the template is empty");
    fs::write(
        &path,
        "# Project principles\n<!-- guidance\nover lines -->\n## Stack\n<!-- hint -->\nRust 1.90\n",
    )?;
    assert_eq!(
        principles(root.path())?.as_deref(),
        Some("# Project principles\n\n## Stack\n\nRust 1.90")
    );
    fs::write(&path, format!("## Never\n{}\n", "x".repeat(40 * 1024)))?;
    assert!(principles(root.path()).is_err());
    Ok(())
}

#[test]
fn stories_are_chosen_by_priority_or_id() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let spec = approved_spec(directory.path())?;
    assert_eq!(select_stories(&spec, None)?, ["US-1"]);
    assert_eq!(select_stories(&spec, Some("US-2, P1"))?, ["US-1", "US-2"]);
    assert!(select_stories(&spec, Some("P3")).is_err());
    let view = planning_view(&spec, &["US-2".into()]);
    assert_eq!(view["requirements"].as_array().map(Vec::len), Some(1));
    Ok(())
}

#[test]
fn coverage_refuses_a_spec_path_that_climbs_out_of_the_repository() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let spec = approved_spec(directory.path())?;
    let mut plan = traced_plan(&spec, &[&["FR-1", "FR-2"]])?;
    plan.spec.as_mut().unwrap().path = "../spec.yaml".into();
    let error = coverage(&plan, directory.path()).unwrap_err();
    assert!(format!("{error:#}").contains("invalid repository-relative path"));
    Ok(())
}

#[test]
fn coverage_rules_c1_to_c4() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let spec = approved_spec(directory.path())?;
    let root = directory.path();

    let (_, warnings) = coverage(&traced_plan(&spec, &[&["FR-1", "SC-1"], &["FR-2"]])?, root)?
        .expect("the plan names a spec");
    assert!(warnings.is_empty(), "{warnings:?}");

    let missing = coverage(&traced_plan(&spec, &[&["FR-1"]])?, root).unwrap_err();
    assert!(missing
        .to_string()
        .starts_with("C2: no acceptance criterion checks FR-2"));

    let unknown = coverage(&traced_plan(&spec, &[&["FR-1", "FR-2", "FR-9"]])?, root).unwrap_err();
    assert!(unknown.to_string().starts_with("C1: a/AC-1 refers to FR-9"));

    let (_, warnings) = coverage(
        &traced_plan(&spec, &[&["FR-1", "FR-2", "FR-3"], &[]])?,
        root,
    )?
    .unwrap();
    assert!(warnings[0].starts_with("C3:") && warnings[0].ends_with("FR-3"));
    assert_eq!(
        warnings[1],
        "C4: acceptance criteria without spec refs: a/AC-2"
    );

    let mut stale = traced_plan(&spec, &[&["FR-1", "FR-2"]])?;
    stale.spec.as_mut().unwrap().digest = format!("sha256:{}", "0".repeat(64));
    assert!(coverage(&stale, root)
        .unwrap_err()
        .to_string()
        .starts_with("C0:"));
    Ok(())
}

#[test]
fn decisions_get_fresh_ids_and_the_next_round() -> Result<()> {
    let mut spec = empty("idea");
    spec["rounds"] = json!(2);
    spec["questions_issued"] = json!(4);
    let records = apply_decisions(
        &mut spec,
        &["  Use weekly totals ".into(), "Keep it local".into()],
    )?;
    assert_eq!(records[0]["id"], "Q-5");
    assert_eq!(records[1]["id"], "Q-6");
    assert_eq!(records[0]["answer"], "Use weekly totals", "text is trimmed");
    assert_eq!(records[0]["round"], 3);
    assert_eq!(records[0]["source"], "free");
    assert_eq!(spec["questions_issued"], 6);
    assert_eq!(array_or_empty(&spec["clarifications"]).len(), 2);
    validate(&spec)?;
    // A blank decision is rejected before it is recorded.
    assert!(apply_decisions(&mut spec, &["   ".into()]).is_err());
    assert_eq!(spec["questions_issued"], 6);
    Ok(())
}

#[test]
fn proceeding_turns_unanswered_questions_into_recommendations() -> Result<()> {
    let mut spec = empty("idea");
    spec["rounds"] = json!(2);
    spec["questions_issued"] = json!(2);
    spec["questions"] = json!([1, 2]
        .iter()
        .map(|n| {
            let mut q = question("scope", "high");
            q["id"] = json!(format!("Q-{n}"));
            q
        })
        .collect::<Vec<_>>());
    let records = apply_answers(&mut spec, &["Q-2=B".into()], true)?;
    assert_eq!(records.len(), 2);
    assert_eq!(records[0]["source"], "option");
    assert_eq!(records[1]["id"], "Q-1");
    assert_eq!(records[1]["source"], "recommended");
    assert_eq!(records[1]["round"], 2);
    assert_eq!(spec["questions"], json!([]));
    assert!(apply_answers(&mut spec.clone(), &["Q-1=".into()], false).is_err());
    Ok(())
}

#[test]
fn readiness_reports_stories_without_scenarios_or_requirements_and_missing_actors() {
    let mut spec = empty("idea");
    spec["problem"] = json!("Orders get lost");
    spec["success_criteria"] = json!([{"id": "SC-1", "text": "Fast"}]);
    spec["out_of_scope"] = json!(["Payments"]);
    spec["stories"] = json!([
        {"id": "US-1", "priority": "P1", "title": "Sell", "scenarios": []},
        {"id": "US-2", "priority": "P2", "title": "Report", "scenarios": ["Given, When, Then"]}]);
    spec["requirements"] = json!([{"id": "FR-1", "story": "US-2", "text": "Totals"}]);
    let failures = readiness(&spec);
    assert_eq!(failures.len(), 3, "{failures:?}");
    assert!(failures[0].starts_with("R3") && failures[0].contains("US-1"));
    assert!(failures[1].starts_with("R4") && failures[1].contains("US-1"));
    assert!(failures[2].starts_with("R7"));
}

#[test]
fn spec_ids_must_look_like_their_prefix() {
    let id = |text: &str, prefix: &str| numbered(&json!(text), prefix, "id").map(|(_, n)| n);
    assert_eq!(id("FR-12", "FR").unwrap(), 12);
    assert_eq!(id("FR-9999", "FR").unwrap(), 9999);
    for bad in ["FR-", "FR-12345", "FR12", "FR-1a", "SC-1", " FR-1"] {
        assert!(id(bad, "FR").is_err(), "{bad:?}");
    }
    let mut seen = BTreeSet::new();
    assert!(unique(&mut seen, &json!("US-1"), "US", "story id").is_ok());
    assert_eq!(
        unique(&mut seen, &json!("US-1"), "US", "story id")
            .unwrap_err()
            .to_string(),
        "duplicate story id US-1"
    );
}

#[test]
fn a_spec_survives_saving_and_loading_with_its_digest() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let spec = approved_spec(directory.path())?;
    let loaded = load(&directory.path().join("spec.yaml"))?;
    assert_eq!(digest(&loaded), digest(&spec));
    assert!(approved(&loaded));
    // Any edit after approval invalidates it.
    let mut edited = loaded;
    edited["problem"] = json!("Something else");
    assert!(!approved(&edited));
    Ok(())
}

#[test]
fn changes_lists_what_a_revision_added_removed_and_changed() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let before = approved_spec(directory.path())?;
    let mut after = before.clone();
    after["requirements"][1]["text"] = json!("Lower the stock");
    after["requirements"]
        .as_array_mut()
        .context("requirements")?
        .remove(2);
    after["requirements"]
        .as_array_mut()
        .context("requirements")?
        .push(json!({"id": "FR-4", "story": "US-1", "text": "Email receipts"}));
    after["out_of_scope"] = json!(["Printed receipts"]);
    let lines = changes(&before, &after);
    assert!(
        lines.contains(&"~ FR-2 Lower the stock".to_owned()),
        "{lines:?}"
    );
    assert!(lines.contains(&"- FR-3 Totals".to_owned()), "{lines:?}");
    assert!(
        lines.contains(&"+ FR-4 Email receipts".to_owned()),
        "{lines:?}"
    );
    assert!(
        lines.contains(&"+ out_of_scope: Printed receipts".to_owned()),
        "{lines:?}"
    );
    // Session fields such as the approval are not part of the change.
    let mut unapproved = before.clone();
    unapproved["approved"] = Value::Null;
    assert!(changes(&before, &unapproved).is_empty());
    Ok(())
}

#[test]
fn approve_shown_locks_only_the_version_whose_code_was_shown() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let path = directory.path().join("spec.yaml");
    let mut spec = approved_spec(directory.path())?;
    spec["approved"] = Value::Null;
    let code = approval_code(&spec);
    assert_eq!(code.len(), 8);

    let mut edited = spec.clone();
    edited["problem"] = json!("Something else");
    let error = approve_shown(&path, &mut edited, &code).unwrap_err();
    assert!(
        error.to_string().contains("changed since approval code"),
        "{error}"
    );
    assert!(!approved(&edited));
    for bad in ["abc", "not-hex!"] {
        assert!(approve_shown(&path, &mut spec, bad).is_err(), "{bad}");
    }

    // Upper case and surrounding spaces are fine; approving twice is too.
    approve_shown(&path, &mut spec, &format!(" {} ", code.to_uppercase()))?;
    assert!(approved(&spec));
    assert!(approved(&load(&path)?));
    approve_shown(&path, &mut spec, &code[..6])?;
    Ok(())
}

#[test]
fn a_kept_draft_is_only_a_cache() -> Result<()> {
    let directory = tempfile::tempdir()?;
    let repo = Repo {
        root: directory.path().into(),
        data: directory.path().join("data"),
        worktrees: directory.path().join("worktrees"),
    };
    let stories = vec!["US-1".to_owned()];
    let drafts = Drafts::new(&repo, ".agengo/spec.yaml", &stories);
    let draft = json!({"tasks": [{"id": "a"}], "questions": ["Print receipts?"]});
    let mut spec = json!({"rounds": 1, "clarifications": []});
    drafts.remember(&draft, &json!(1))?;
    // Nothing decided since the draft: nothing to revise.
    assert_eq!(drafts.previous(&spec)?, None);
    spec["clarifications"] = json!([{"round": 2, "question": DECISION, "answer": "No"}]);
    let previous = drafts.previous(&spec)?.context("draft kept")?;
    assert_eq!(previous["decisions"], json!([{"answer": "No"}]));
    assert_eq!(previous["tasks"], draft["tasks"]);

    // Another story selection has its own draft.
    let other = Drafts::new(&repo, ".agengo/spec.yaml", &["US-2".to_owned()]);
    assert_eq!(other.previous(&spec)?, None);

    // A stale or damaged draft is ignored, not an error.
    let mut kept: Value = serde_json::from_str(&fs::read_to_string(&drafts.file)?)?;
    kept["saved_at"] = json!(now_seconds() - DRAFT_MAX_AGE - 1);
    fs::write(&drafts.file, serde_json::to_vec(&kept)?)?;
    assert_eq!(drafts.previous(&spec)?, None);
    fs::write(&drafts.file, "{\"spec\": \".agengo/sp")?;
    assert_eq!(drafts.previous(&spec)?, None);

    drafts.forget()?;
    assert!(!drafts.file.exists());
    drafts.forget()?;
    Ok(())
}