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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `agengo spec`: turn a rough idea into an approved, user-facing specification.
//!
//! The spec file is the session state. Every round sends the current spec and
//! the new answers to the `specify` role; agengo itself chooses, numbers and
//! limits the questions, so the limits do not depend on the agent obeying its
//! prompt. See docs/design/spec-stage.md.

mod drafts;
mod plan_link;
#[cfg(test)]
mod tests;
mod validate;

pub use drafts::*;
pub use plan_link::*;
use validate::*;

use crate::{
    adapter,
    contract::{self, array_or_empty, string_or_empty, text},
    plan::{Plan, Task},
    process::Repo,
    store::Store,
};
use anyhow::{bail, Context, Result};
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use std::{
    collections::BTreeSet,
    fs,
    io::Write,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

/// How thoroughly to interview: (name, questions kept open per round,
/// rounds). The last round turns every remaining uncertainty into an
/// assumption. The agent asks fewer when fewer matter; these are ceilings.
pub const DEPTHS: [(&str, usize, u64); 3] = [("quick", 3, 2), ("standard", 5, 3), ("deep", 8, 4)];
pub const DEFAULT_DEPTH: &str = "standard";
/// Options per question: the most a chat app's choice prompt shows (Claude
/// Code's AskUserQuestion takes 2 to 4, plus its own free-text option).
pub const MAX_OPTIONS: usize = 4;
/// The question recorded for a decision made after the interview.
const DECISION: &str = "Decision made after the interview";

/// Question categories, most important first. There is deliberately no
/// technology category: the agent decides those and records assumptions.
const CATEGORIES: [&str; 10] = [
    "scope",
    "actors",
    "quality",
    "flow",
    "data",
    "integration",
    "edge_cases",
    "constraints",
    "completion",
    "terminology",
];
const IMPACTS: [&str; 3] = ["high", "medium", "low"];
const PRIORITIES: [&str; 3] = ["P1", "P2", "P3"];
const SOURCES: [&str; 3] = ["option", "recommended", "free"];
/// Sections the agent writes.
const BODY: [&str; 9] = [
    "problem",
    "actors",
    "stories",
    "requirements",
    "success_criteria",
    "out_of_scope",
    "constraints",
    "assumptions",
    "feasibility",
];
/// Sections only agengo writes.
const SESSION: [&str; 8] = [
    "schema_version",
    "idea",
    "questions",
    "clarifications",
    "depth",
    "rounds",
    "questions_issued",
    "approved",
];
/// Key order in the written YAML, so the file reads top-down for a person.
const KEY_ORDER: [&str; 38] = [
    "schema_version",
    "idea",
    "problem",
    "actors",
    "stories",
    "requirements",
    "success_criteria",
    "out_of_scope",
    "constraints",
    "assumptions",
    "feasibility",
    "questions",
    "clarifications",
    "depth",
    "rounds",
    "questions_issued",
    "approved",
    "round",
    "id",
    "priority",
    "story",
    "category",
    "impact",
    "key",
    "label",
    "title",
    "question",
    "text",
    "why",
    "answer",
    "source",
    "implication",
    "if_wrong",
    "options",
    "recommended",
    "scenarios",
    "digest",
    "at",
];

pub struct Command {
    pub idea: Option<String>,
    pub path: Option<PathBuf>,
    pub output: Option<PathBuf>,
    pub force: bool,
    pub answers: Vec<String>,
    /// Decisions made after the interview, such as answers to the planner's
    /// questions; each revises the spec like an answer.
    pub decisions: Vec<String>,
    pub proceed: bool,
    pub approve: bool,
    /// One of `DEPTHS`; `None` keeps the spec's depth (standard when new).
    pub depth: Option<String>,
    pub json: bool,
    pub agent: Option<String>,
    pub auth: adapter::Auth,
    pub timeout: u64,
    pub roles: Option<PathBuf>,
}

/// Where a repository keeps the project's own rules for agents.
pub const PRINCIPLES_PATH: &str = ".agengo/principles.md";
/// Where `agengo spec --idea` writes the spec unless `--output` says otherwise.
pub const SPEC_PATH: &str = ".agengo/spec.yaml";
/// More than this is no longer a short list of rules, and every spec and
/// plan request would carry it.
const PRINCIPLES_LIMIT: usize = 32 * 1024;

/// The project's principles for the spec and plan agents, without the
/// template's guidance comments, or `None` when the file is missing or every
/// section is still empty.
/// `principles`, with a note on stderr when there are none, because the agents
/// then guess the project's stack and commands.
pub fn principles_or_note(root: &Path) -> Result<Option<String>> {
    let found = principles(root)?;
    if found.is_none() {
        eprintln!(
            "agengo: note: no project principles ({PRINCIPLES_PATH} is missing or empty), so the agent will infer your stack and commands. Run `agengo init` if it is missing, then fill it in."
        );
    }
    Ok(found)
}

pub fn principles(root: &Path) -> Result<Option<String>> {
    let path = root.join(PRINCIPLES_PATH);
    let text = match fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error).with_context(|| format!("cannot read {}", path.display())),
    };
    let mut kept = String::new();
    let mut rest = text.as_str();
    while let Some(start) = rest.find("<!--") {
        kept.push_str(&rest[..start]);
        rest = rest[start..]
            .find("-->")
            .map_or("", |end| &rest[start + end + 3..]);
    }
    kept.push_str(rest);
    let kept: String = kept
        .lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n");
    let filled = kept
        .lines()
        .any(|line| !line.trim().is_empty() && !line.trim_start().starts_with('#'));
    if !filled {
        return Ok(None);
    }
    if kept.len() > PRINCIPLES_LIMIT {
        bail!(
            "{} is longer than {} KiB; keep it to the rules agents need",
            path.display(),
            PRINCIPLES_LIMIT / 1024
        );
    }
    Ok(Some(kept.trim().to_owned()))
}

/// Exit code 2 means questions are waiting for the user, as for `run`.
pub fn execute(cwd: &Path, command: Command) -> Result<i32> {
    let (mut spec, path, fresh) = match (&command.idea, &command.path) {
        (Some(idea), None) => {
            let path = command
                .output
                .clone()
                .unwrap_or_else(|| PathBuf::from(SPEC_PATH));
            if path.exists() && !command.force {
                bail!(
                    "{} already exists; pass --force to replace it",
                    path.display()
                );
            }
            let idea = json!(idea);
            (empty(text(&idea, "idea")?), path, true)
        }
        (None, Some(path)) => (load(path)?, path.clone(), false),
        _ => bail!("pass either --idea or a spec file"),
    };
    let mut changed = false;
    if let Some(depth) = &command.depth {
        if !DEPTHS.iter().any(|(name, ..)| name == depth) {
            bail!("unknown depth {depth}; use quick, standard or deep");
        }
        changed = spec["depth"] != json!(depth);
        spec["depth"] = json!(depth);
    }
    if command.approve {
        lock(&path, &mut spec)?;
        report(&spec, &path, None, command.json)?;
        return Ok(0);
    }
    // What the person approves next is the difference this round makes.
    let before = (!fresh).then(|| spec.clone());
    let mut answers = apply_answers(&mut spec, &command.answers, command.proceed)?;
    answers.extend(apply_decisions(&mut spec, &command.decisions)?);
    if fresh || !answers.is_empty() {
        let round = spec["rounds"].as_u64().unwrap_or(0) + 1;
        let (max_questions, max_rounds) = limits(&spec);
        let finalize = round >= max_rounds || command.proceed;
        let repo = Repo::open(cwd)?;
        let profile = contract::profile(command.roles.as_deref())?;
        let agent = adapter::select(command.agent.as_deref(), &repo.root)?;
        let request = json!({
            "schema_version": 1,
            "role": "specify",
            "idea": spec["idea"],
            "spec": if fresh { Value::Null } else { body(&spec) },
            "answers": answers
                .iter()
                .map(|item| json!({"id": item["id"], "question": item["question"], "answer": item["answer"]}))
                .collect::<Vec<_>>(),
            "round": round,
            "finalize": finalize,
            "depth": spec["depth"],
            "max_questions": if finalize { 0 } else { max_questions },
            "principles": principles_or_note(&repo.root)?,
        });
        eprintln!(
            "agengo: spec round {round} · {} · timeout {}s",
            adapter::label(agent.as_deref(), command.auth),
            command.timeout
        );
        let invocation = adapter::invoke_measured(
            agent.as_deref(),
            command.auth,
            &request,
            &repo.root,
            command.timeout,
            &profile,
            &crate::config::load(&repo.root)?,
        );
        if let Some(summary) = invocation
            .usage
            .as_ref()
            .and_then(crate::usage::describe_call)
        {
            eprintln!("agengo: spec round {round} used {summary}");
        }
        let reply = invocation.reply?;
        revise(&mut spec, &reply, finalize).context("invalid specify reply")?;
        spec["rounds"] = json!(round);
        spec["approved"] = Value::Null;
        validate(&spec)?;
        save(&path, &spec)?;
        let revised = before.map(|before| changes(&before, &spec));
        report(&spec, &path, revised.as_deref(), command.json)?;
        return Ok(exit_code(&spec));
    } else if changed {
        spec["approved"] = Value::Null;
        save(&path, &spec)?;
    }
    report(&spec, &path, None, command.json)?;
    Ok(exit_code(&spec))
}

/// Exit code 2 while questions are open, as for `run`.
fn exit_code(spec: &Value) -> i32 {
    if array_or_empty(&spec["questions"]).is_empty() {
        0
    } else {
        2
    }
}

/// Checks readiness and locks the spec with its digest.
fn lock(path: &Path, spec: &mut Value) -> Result<()> {
    let failures = readiness(spec);
    if !failures.is_empty() {
        bail!(
            "{} is not ready to approve:\n- {}",
            path.display(),
            failures.join("\n- ")
        );
    }
    spec["approved"] = json!({"digest": digest(spec), "at": timestamp()});
    save(path, spec)
}

/// Shortest approval code agengo accepts: long enough that an edited spec
/// cannot match the code shown for the reviewed one by chance.
const APPROVAL_CODE_MIN: usize = 6;

/// The code a person passes to approve exactly this version of the spec: the
/// start of its digest.
pub fn approval_code(spec: &Value) -> String {
    digest(spec)["sha256:".len()..][..8].to_owned()
}

/// Approves the spec at `path` only if it is still the version whose approval
/// code was shown, so what gets approved is what the person reviewed. An
/// already approved spec with a matching code is left as it is.
pub fn approve_shown(path: &Path, spec: &mut Value, code: &str) -> Result<()> {
    let code = code.trim().to_ascii_lowercase();
    if code.len() < APPROVAL_CODE_MIN || !code.chars().all(|c| c.is_ascii_hexdigit()) {
        bail!(
            "approval code {code:?} is not valid; use the code agengo spec printed for the version you reviewed"
        );
    }
    let current = digest(spec);
    if !current["sha256:".len()..].starts_with(&code) {
        bail!(
            "{} changed since approval code {code} was shown (it is now {}); review it again with agengo spec {}",
            path.display(),
            approval_code(spec),
            shell_word(path)
        );
    }
    if approved(spec) {
        return Ok(());
    }
    lock(path, spec)
}

/// Items a revision added (`+`), removed (`-`) or changed (`~`) in the parts
/// of the spec a person approves, one line each.
pub fn changes(before: &Value, after: &Value) -> Vec<String> {
    let mut lines = Vec::new();
    if before["problem"] != after["problem"] {
        lines.push(format!("~ problem: {}", string_or_empty(&after["problem"])));
    }
    for (key, label) in [
        ("stories", "title"),
        ("requirements", "text"),
        ("success_criteria", "text"),
        ("assumptions", "text"),
    ] {
        let old = array_or_empty(&before[key]);
        let new = array_or_empty(&after[key]);
        let find =
            |items: &[Value], id: &Value| items.iter().find(|item| item["id"] == *id).cloned();
        for item in new {
            let line = format!(
                "{} {}",
                string_or_empty(&item["id"]),
                string_or_empty(&item[label])
            );
            match find(old, &item["id"]) {
                None => lines.push(format!("+ {line}")),
                Some(previous) if previous != *item => lines.push(format!("~ {line}")),
                Some(_) => {}
            }
        }
        for item in old.iter().filter(|item| find(new, &item["id"]).is_none()) {
            lines.push(format!(
                "- {} {}",
                string_or_empty(&item["id"]),
                string_or_empty(&item[label])
            ));
        }
    }
    for key in ["actors", "out_of_scope", "constraints", "feasibility"] {
        let old = array_or_empty(&before[key]);
        let new = array_or_empty(&after[key]);
        for item in new.iter().filter(|item| !old.contains(item)) {
            lines.push(format!("+ {key}: {}", string_or_empty(item)));
        }
        for item in old.iter().filter(|item| !new.contains(item)) {
            lines.push(format!("- {key}: {}", string_or_empty(item)));
        }
    }
    lines
}

fn empty(idea: &str) -> Value {
    json!({
        "schema_version": 1, "idea": idea, "problem": "", "actors": [], "stories": [],
        "requirements": [], "success_criteria": [], "out_of_scope": [], "constraints": [],
        "assumptions": [], "feasibility": [], "questions": [], "clarifications": [],
        "depth": DEFAULT_DEPTH, "rounds": 0, "questions_issued": 0, "approved": null,
    })
}

/// (questions kept open per round, rounds) for the spec's depth.
fn limits(spec: &Value) -> (usize, u64) {
    let depth = spec["depth"].as_str().unwrap_or(DEFAULT_DEPTH);
    DEPTHS
        .iter()
        .find(|(name, ..)| *name == depth)
        .map_or((5, 3), |(_, questions, rounds)| (*questions, *rounds))
}

/// The sections the agent revises, without agengo's session fields.
fn body(spec: &Value) -> Value {
    Value::Object(
        BODY.iter()
            .map(|key| ((*key).to_owned(), spec[*key].clone()))
            .collect(),
    )
}

pub fn load(path: &Path) -> Result<Value> {
    let source =
        fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
    let mut spec: Value = serde_yaml_ng::from_str(&source)
        .with_context(|| format!("{} is not valid YAML or JSON", path.display()))?;
    // Specs written before `depth` existed used the standard limits.
    if let Some(fields) = spec.as_object_mut() {
        fields
            .entry("depth")
            .or_insert_with(|| json!(DEFAULT_DEPTH));
    }
    validate(&spec).with_context(|| format!("invalid spec {}", path.display()))?;
    Ok(spec)
}

fn save(path: &Path, spec: &Value) -> Result<()> {
    let yaml = serde_yaml_ng::to_string(&ordered(spec)?)?;
    let directory = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    // The default path is inside `.agengo/`, which may not exist yet.
    fs::create_dir_all(directory)
        .with_context(|| format!("cannot create {}", directory.display()))?;
    // Write next to the target and rename, so an interrupted write never
    // leaves a truncated spec behind.
    let mut file = tempfile::NamedTempFile::new_in(directory)?;
    file.write_all(yaml.as_bytes())?;
    // A temporary file is private; give the spec the usual file mode.
    #[cfg(unix)]
    file.as_file()
        .set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o644))?;
    file.persist(path)
        .with_context(|| format!("cannot write {}", path.display()))?;
    Ok(())
}

fn ordered(value: &Value) -> Result<serde_yaml_ng::Value> {
    Ok(match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort_by_key(|key| {
                (
                    KEY_ORDER
                        .iter()
                        .position(|known| known == key)
                        .unwrap_or(KEY_ORDER.len()),
                    (*key).clone(),
                )
            });
            let mut mapping = serde_yaml_ng::Mapping::new();
            for key in keys {
                mapping.insert(
                    serde_yaml_ng::Value::String(key.clone()),
                    ordered(&map[key])?,
                );
            }
            serde_yaml_ng::Value::Mapping(mapping)
        }
        Value::Array(items) => {
            serde_yaml_ng::Value::Sequence(items.iter().map(ordered).collect::<Result<_>>()?)
        }
        other => serde_yaml_ng::to_value(other)?,
    })
}

/// Moves answered questions into `clarifications` and returns the new records.
fn apply_answers(spec: &mut Value, answers: &[String], proceed: bool) -> Result<Vec<Value>> {
    // Questions belong to the round that asked them.
    let round = spec["rounds"].as_u64().unwrap_or(0).max(1);
    let mut open = array_or_empty(&spec["questions"]).to_vec();
    let mut records = Vec::new();
    for answer in answers {
        let (id, value) = answer
            .split_once('=')
            .with_context(|| format!("expected Q-n=VALUE, got {answer:?}"))?;
        let (id, value) = (id.trim(), value.trim());
        if value.is_empty() {
            bail!("the answer to {id} is empty");
        }
        let index = open
            .iter()
            .position(|question| question["id"] == id)
            .with_context(|| format!("{id} is not an open question in this spec"))?;
        let question = open.remove(index);
        records.push(record(&question, Some(value), round));
    }
    if proceed {
        records.extend(
            open.drain(..)
                .map(|question| record(&question, None, round)),
        );
    }
    spec["questions"] = json!(open);
    spec["clarifications"]
        .as_array_mut()
        .context("clarifications must be a list")?
        .extend(records.iter().cloned());
    Ok(records)
}

/// Records each decision as a clarification under a fresh question ID, so
/// the spec keeps every decision the user made, whoever asked for it.
fn apply_decisions(spec: &mut Value, decisions: &[String]) -> Result<Vec<Value>> {
    // A decision belongs to the round that applies it.
    let round = spec["rounds"].as_u64().unwrap_or(0) + 1;
    let mut issued = counter(spec, "questions_issued")?;
    let mut records = Vec::new();
    for decision in decisions {
        let decision = json!(decision.trim());
        let decision = text(&decision, "decision")?;
        issued += 1;
        records.push(json!({
            "round": round, "id": format!("Q-{issued}"), "question": DECISION,
            "answer": decision, "source": "free",
        }));
    }
    spec["questions_issued"] = json!(issued);
    spec["clarifications"]
        .as_array_mut()
        .context("clarifications must be a list")?
        .extend(records.iter().cloned());
    Ok(records)
}

/// An option key picks that option, `yes` (or no value) the recommendation,
/// and anything else is the user's own answer.
fn record(question: &Value, value: Option<&str>, round: u64) -> Value {
    let label = |key: &str| {
        array_or_empty(&question["options"])
            .iter()
            .find(|option| string_or_empty(&option["key"]).eq_ignore_ascii_case(key))
            .map(|option| string_or_empty(&option["label"]).to_owned())
    };
    let recommended = string_or_empty(&question["recommended"]);
    let (answer, source) = match value {
        None => (label(recommended), "recommended"),
        Some(value) if value.eq_ignore_ascii_case("yes") => (label(recommended), "recommended"),
        Some(value) => match label(value) {
            Some(label) => (Some(label), "option"),
            None => (Some(value.to_owned()), "free"),
        },
    };
    json!({
        "round": round, "id": question["id"], "question": question["question"],
        "answer": answer.unwrap_or_default(), "source": source,
    })
}

/// Takes the agent's revised sections and keeps at most the depth's limit of
/// its candidate questions, most important first, under fresh IDs.
fn revise(spec: &mut Value, reply: &Value, finalize: bool) -> Result<()> {
    if reply
        .get("schema_version")
        .is_some_and(|version| version.as_u64() != Some(1))
    {
        bail!("unsupported schema_version; expected 1");
    }
    let mut allowed = BODY.to_vec();
    allowed.extend(["candidate_questions", "schema_version"]);
    contract::fields(reply, "reply", &allowed)?;
    for key in BODY {
        spec[key] = reply
            .get(key)
            .with_context(|| format!("missing {key}"))?
            .clone();
    }
    validate_body(spec)?;
    let candidates = list(reply, "candidate_questions")?;
    if finalize {
        if !candidates.is_empty() {
            eprintln!(
                "agengo: ignored {} because this is the final round",
                contract::count(candidates.len(), "question")
            );
        }
        spec["questions"] = json!([]);
        return Ok(());
    }
    let mut accepted = Vec::new();
    for candidate in candidates {
        match question_problem(candidate, false) {
            None => accepted.push(candidate.clone()),
            Some(problem) => eprintln!(
                "agengo: dropped a question that breaks the question rules ({problem}): {}",
                string_or_empty(&candidate["question"])
            ),
        }
    }
    // A stable sort keeps the agent's order within the same rank.
    accepted.sort_by_key(|question| {
        (
            rank(&IMPACTS, &question["impact"]),
            rank(&CATEGORIES, &question["category"]),
        )
    });
    let (max_questions, _) = limits(spec);
    if accepted.len() > max_questions {
        eprintln!(
            "agengo: kept the {max_questions} most important of {} questions",
            accepted.len()
        );
        accepted.truncate(max_questions);
    }
    // IDs keep counting across rounds, so an ID never names two questions.
    let mut issued = counter(spec, "questions_issued")?;
    let questions: Vec<Value> = accepted
        .into_iter()
        .map(|question| {
            issued += 1;
            let mut numbered = Map::new();
            numbered.insert("id".into(), json!(format!("Q-{issued}")));
            if let Value::Object(fields) = question {
                numbered.extend(fields);
            }
            Value::Object(numbered)
        })
        .collect();
    spec["questions"] = json!(questions);
    spec["questions_issued"] = json!(issued);
    Ok(())
}

fn rank(order: &[&str], value: &Value) -> usize {
    let value = string_or_empty(value);
    order
        .iter()
        .position(|item| *item == value)
        .unwrap_or(order.len())
}

/// Readiness rules R1–R7; an empty list means the spec can be approved.
pub fn readiness(spec: &Value) -> Vec<String> {
    let id = |item: &Value| string_or_empty(&item["id"]).to_owned();
    let mut failures = Vec::new();
    let high: Vec<_> = array_or_empty(&spec["questions"])
        .iter()
        .filter(|question| question["impact"] == "high")
        .map(id)
        .collect();
    if !high.is_empty() {
        failures.push(format!(
            "R1: answer the high-impact questions {}",
            high.join(", ")
        ));
    }
    let stories = array_or_empty(&spec["stories"]);
    let p1: Vec<_> = stories
        .iter()
        .filter(|story| story["priority"] == "P1")
        .collect();
    if p1.is_empty() {
        failures.push("R2: no P1 story".into());
    }
    let bare: Vec<_> = stories
        .iter()
        .filter(|story| array_or_empty(&story["scenarios"]).is_empty())
        .map(id)
        .collect();
    if !bare.is_empty() {
        failures.push(format!(
            "R3: stories without a scenario: {}",
            bare.join(", ")
        ));
    }
    let requirements = array_or_empty(&spec["requirements"]);
    let uncovered: Vec<_> = p1
        .iter()
        .filter(|story| !requirements.iter().any(|item| item["story"] == story["id"]))
        .map(|story| id(story))
        .collect();
    if !uncovered.is_empty() {
        failures.push(format!(
            "R4: P1 stories without a requirement: {}",
            uncovered.join(", ")
        ));
    }
    if array_or_empty(&spec["success_criteria"]).is_empty() {
        failures.push("R5: no success criterion".into());
    }
    if array_or_empty(&spec["out_of_scope"]).is_empty() {
        failures.push("R6: out_of_scope is empty; name what will not be built".into());
    }
    if string_or_empty(&spec["problem"]).trim().is_empty()
        || array_or_empty(&spec["actors"]).is_empty()
    {
        failures.push("R7: problem and actors must be stated".into());
    }
    failures
}

/// `sha256:` of the spec without its `approved` field, as JSON with sorted
/// keys, so reformatting the YAML does not change it but any edit does.
pub fn digest(spec: &Value) -> String {
    let mut unapproved = spec.clone();
    if let Some(fields) = unapproved.as_object_mut() {
        fields.remove("approved");
    }
    let mut canonical = String::new();
    write_canonical(&unapproved, &mut canonical);
    let hash = Sha256::digest(canonical.as_bytes());
    format!(
        "sha256:{}",
        hash.iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>()
    )
}

fn write_canonical(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (index, key) in keys.into_iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                out.push_str(&Value::String(key.clone()).to_string());
                out.push(':');
                write_canonical(&map[key], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        other => out.push_str(&other.to_string()),
    }
}

/// The stories a plan covers: `selection` lists priorities (`P1`) or story
/// IDs (`US-2`), comma-separated, and defaults to the P1 stories. The result
/// keeps the spec's order.
pub fn select_stories(spec: &Value, selection: Option<&str>) -> Result<Vec<String>> {
    let stories = array_or_empty(&spec["stories"]);
    let wanted: Vec<&str> = selection
        .unwrap_or("P1")
        .split(',')
        .map(str::trim)
        .filter(|item| !item.is_empty())
        .collect();
    if wanted.is_empty() {
        bail!("--stories needs priorities such as P1 or story IDs such as US-1");
    }
    let matches = |story: &Value, item: &str| story["priority"] == item || story["id"] == item;
    if let Some(item) = wanted
        .iter()
        .find(|item| !stories.iter().any(|story| matches(story, item)))
    {
        bail!("no story in the spec matches {item}");
    }
    Ok(stories
        .iter()
        .filter(|story| wanted.iter().any(|item| matches(story, item)))
        .map(|story| string_or_empty(&story["id"]).to_owned())
        .collect())
}

fn chosen<'a>(spec: &'a Value, key: &str, field: &str, ids: &[String]) -> Vec<&'a Value> {
    array_or_empty(&spec[key])
        .iter()
        .filter(|item| ids.iter().any(|id| item[field] == id.as_str()))
        .collect()
}

/// What the planner sees: the chosen stories and their requirements, plus
/// the parts of the spec that bound every story.
pub fn planning_view(spec: &Value, stories: &[String]) -> Value {
    json!({
        "problem": spec["problem"], "actors": spec["actors"],
        "stories": chosen(spec, "stories", "id", stories),
        "requirements": chosen(spec, "requirements", "story", stories),
        "success_criteria": spec["success_criteria"], "out_of_scope": spec["out_of_scope"],
        "constraints": spec["constraints"], "assumptions": spec["assumptions"],
        "feasibility": spec["feasibility"],
    })
}

/// Whether the spec was approved and has not changed since.
pub fn approved(spec: &Value) -> bool {
    spec["approved"]["digest"].as_str() == Some(digest(spec).as_str())
}

fn timestamp() -> String {
    civil(now_seconds())
}

/// RFC 3339 UTC time from Unix seconds (Howard Hinnant's civil-from-days).
fn civil(seconds: u64) -> String {
    let (days, rest) = ((seconds / 86_400) as i64, seconds % 86_400);
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
        rest / 3_600,
        rest % 3_600 / 60,
        rest % 60
    )
}

fn shell_word(path: &Path) -> String {
    let text = path.display().to_string();
    if text.chars().any(char::is_whitespace) {
        format!("'{text}'")
    } else {
        text
    }
}

/// `changes` lists what this round revised in an existing spec.
fn report(spec: &Value, path: &Path, changes: Option<&[String]>, json: bool) -> Result<()> {
    let failures = readiness(spec);
    let approved = approved(spec);
    let questions = array_or_empty(&spec["questions"]);
    // Offered only when approving is the next step.
    let code =
        (!approved && questions.is_empty() && failures.is_empty()).then(|| approval_code(spec));
    if json {
        let mut summary = json!({
            "path": path.display().to_string(), "round": spec["rounds"], "depth": spec["depth"],
            "questions": questions,
            "readiness": {"ready": failures.is_empty(), "failures": failures},
            "approved": approved,
        });
        if let Some(changes) = changes {
            summary["changes"] = json!(changes);
        }
        if let Some(code) = &code {
            summary["approval_code"] = json!(code);
        }
        println!("{}", serde_json::to_string_pretty(&summary)?);
        return Ok(());
    }
    let state = if approved {
        "approved"
    } else if !questions.is_empty() {
        "waiting for answers"
    } else if failures.is_empty() {
        "ready to approve"
    } else {
        "not ready"
    };
    let file = shell_word(path);
    let rounds = spec["rounds"].as_u64().unwrap_or(0);
    let (_, max_rounds) = limits(spec);
    // `--decision` adds rounds after the interview's last one.
    let round = if rounds > max_rounds {
        format!("round {rounds}, after the interview")
    } else {
        format!("round {rounds} of {max_rounds}")
    };
    println!(
        "[SPEC] {file} · {round} ({} depth) · {state}",
        string_or_empty(&spec["depth"])
    );
    let problem = string_or_empty(&spec["problem"]);
    if !problem.trim().is_empty() {
        println!("Problem: {problem}");
    }
    match changes {
        Some([]) => println!(
            "Changed this round: nothing in the problem, stories, requirements, success criteria, scope or assumptions"
        ),
        Some(changes) => {
            println!("Changed this round:");
            for change in changes {
                println!("  {change}");
            }
        }
        None => {}
    }
    if !questions.is_empty() {
        for question in questions {
            println!(
                "\n{} [{} · {}] {}",
                string_or_empty(&question["id"]),
                string_or_empty(&question["category"]),
                string_or_empty(&question["impact"]),
                string_or_empty(&question["question"])
            );
            println!("    Why: {}", string_or_empty(&question["why"]));
            let recommended = string_or_empty(&question["recommended"]);
            for option in array_or_empty(&question["options"]) {
                let key = string_or_empty(&option["key"]);
                println!(
                    "    {key}) {}: {}{}",
                    string_or_empty(&option["label"]),
                    string_or_empty(&option["implication"]),
                    if key.eq_ignore_ascii_case(recommended) {
                        "  ★ recommended"
                    } else {
                        ""
                    }
                );
            }
        }
        println!(
            "\nCommand — agengo spec {file} --answer {}=<option key, yes, or your own words> (repeat per question), or --proceed to accept every recommendation",
            string_or_empty(&questions[0]["id"])
        );
        return Ok(());
    }
    for story in array_or_empty(&spec["stories"]) {
        println!(
            "- {} [{}] {}",
            string_or_empty(&story["id"]),
            string_or_empty(&story["priority"]),
            string_or_empty(&story["title"])
        );
    }
    let out_of_scope: Vec<_> = array_or_empty(&spec["out_of_scope"])
        .iter()
        .map(string_or_empty)
        .collect();
    if !out_of_scope.is_empty() {
        println!("Not built: {}", out_of_scope.join("; "));
    }
    // Approving the spec confirms these, so show every assumption that
    // matters; low-impact ones stay in the file.
    for impact in ["high", "medium"] {
        for assumption in array_or_empty(&spec["assumptions"])
            .iter()
            .filter(|item| item["impact"] == impact)
        {
            println!(
                "Assumed {} [{impact}]: {} (if wrong: {})",
                string_or_empty(&assumption["id"]),
                string_or_empty(&assumption["text"]),
                string_or_empty(&assumption["if_wrong"])
            );
        }
    }
    for note in array_or_empty(&spec["feasibility"]) {
        println!("Feasibility: {}", string_or_empty(note));
    }
    for failure in &failures {
        println!("Not ready — {failure}");
    }
    if let Some(code) = code {
        println!("Command — agengo spec {file} --approve");
        println!("Command — agengo plan --spec {file} --approve-spec {code}   (approve this version and draft the plan)");
    }
    Ok(())
}