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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
mod adapter;
mod agent;
mod agent_check;
mod config;
mod context;
mod contract;
mod control;
mod detect;
mod doctor;
mod driver;
mod engine;
mod failure;
mod handoff;
mod inbox;
mod init;
mod integrity;
mod metrics;
mod plan;
mod platform;
mod process;
mod quality;
mod sandbox;
mod setup;
mod spec;
mod store;
mod usage;
mod verification;

use anyhow::{bail, Context, Result};
use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum};
use contract::{array_or_empty, count, identifier, string_or_empty, text};
use process::{Repo, INTERRUPTED};
use rusqlite::params;
use serde_json::{json, Value};
use std::{path::PathBuf, sync::atomic::Ordering};
use store::{show, Store};

#[derive(Parser)]
#[command(version, about = "Build, review and integrate a Git work plan")]
struct Cli {
    #[arg(short = 'C', long, global = true, default_value = ".")]
    repo: PathBuf,
    /// How far to confine agents: off (as before), auto (use the agent's OS
    /// sandbox where agengo can enable it; pass only a short list of
    /// environment variables) or strict (as auto, but refuse an agent whose
    /// sandbox agengo cannot enforce). Overrides `sandbox:` in the config file.
    #[arg(long, global = true, value_enum)]
    sandbox: Option<config::Sandbox>,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Turn a rough idea into an approved spec by answering a few questions.
    Spec(Spec),
    /// Validate a plan or draft one from a goal or existing plan.
    Plan(Plan),
    /// Start a run from a YAML or JSON plan.
    Run(Run),
    /// Recover or continue a run.
    Resume {
        run_id: String,
        #[arg(long)]
        task: Option<String>,
        /// Continue with this agent instead of the one the run started with
        /// (claude, codex, agy or a custom adapter path).
        #[arg(long, conflicts_with = "task")]
        agent: Option<String>,
    },
    /// Show plan, tasks and evidence.
    Status {
        run_id: String,
        #[arg(long)]
        json: bool,
        /// Print the status and cost again until the run ends, waits for you, or stops.
        #[arg(long, conflicts_with = "json")]
        watch: bool,
        /// Seconds between two --watch reports.
        #[arg(long, value_name = "SECONDS", default_value = "10", value_parser = positive, requires = "watch")]
        interval: u64,
    },
    /// List decisions and replies awaiting action.
    Inbox {
        run_id: String,
        #[arg(long)]
        json: bool,
    },
    /// Summarize recorded attempt durations, repeated assignments and reliability.
    #[command(group(ArgGroup::new("target").required(true).args(["run_id", "all"])))]
    Metrics {
        run_id: Option<String>,
        /// Report every run in the state database with a combined row.
        #[arg(long)]
        all: bool,
        #[arg(long)]
        json: bool,
    },
    /// Record a decision and reopen a blocked task.
    Resolve {
        run_id: String,
        task_id: String,
        #[arg(long)]
        note: String,
    },
    /// Answer a request by its Y- code.
    Respond {
        run_id: String,
        code: String,
        #[arg(long, value_enum, ignore_case = true)]
        choice: Option<Choice>,
        #[arg(long)]
        note: Option<String>,
        #[arg(long)]
        plan: Option<PathBuf>,
    },
    /// Pause a task before its next workflow step.
    Pause {
        run_id: String,
        #[arg(long)]
        task: String,
    },
    /// Approve a new revision of the plan.
    Amend {
        run_id: String,
        plan_file: PathBuf,
        #[arg(long)]
        note: String,
    },
    /// Remove a run's worktrees; for a delivered run also its temporary refs.
    Clean { run_id: String },
    /// Install the agengo skill so coding agents in this repository know when to call agengo.
    Init {
        /// Do not add the agengo section to AGENTS.md.
        #[arg(long)]
        no_agents_md: bool,
    },
    /// Check that git, the repository and a coding agent are ready for a run.
    Doctor {
        /// Print the checks as JSON (level, code and text of each), for a coding agent to read.
        #[arg(long)]
        json: bool,
    },
    /// Print what this Linux or WSL2 machine still needs (packages, agents on PATH, logins); with --apply, install the missing packages.
    Setup {
        /// Run the package installation (apt-get) instead of only printing it.
        #[arg(long)]
        apply: bool,
    },
    /// Show the coding agents installed and which one commands use, or choose one.
    Agent {
        #[command(subcommand)]
        action: Option<AgentAction>,
    },
    /// Show or change the repository's settings in `.agengo/config.yaml`.
    Config {
        #[command(subcommand)]
        action: Option<ConfigAction>,
    },
    /// Validate a YAML role catalog and its prompt references.
    Roles {
        #[arg(long)]
        file: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// Set KEY to VALUE: agent, think.model, think.effort (low|medium|high|max), build.model, build.effort, think.models.AGENT, build.models.AGENT.
    Set { key: String, value: String },
    /// Remove KEY, so the agent's own default applies again.
    Unset { key: String },
}

#[derive(Subcommand)]
enum AgentAction {
    /// Use NAME (claude, codex, agy or the path of a custom adapter) in this repository; `auto` uses the only agent installed again.
    Use { name: String },
    /// Ask the agent (NAME, or the one chosen) to write a file and run a command in a scratch repository, the way a run needs it, and say what it could not do.
    Check { name: Option<String> },
}

#[derive(Args)]
#[command(group(ArgGroup::new("source").required(true).args(["idea", "file"])))]
struct Spec {
    /// Start a new spec from an idea in your own words.
    #[arg(long)]
    idea: Option<String>,
    /// An existing spec to answer, approve or show.
    file: Option<PathBuf>,
    /// Where --idea writes the spec.
    /// Default: .agengo/spec.yaml.
    #[arg(short, long, requires = "idea", value_name = "PATH")]
    output: Option<PathBuf>,
    /// Replace an existing file at the --idea output path.
    #[arg(long, requires = "idea")]
    force: bool,
    /// Answer an open question: Q-n=KEY, Q-n=yes (take the recommendation) or Q-n="your own words".
    #[arg(long = "answer", value_name = "Q-n=VALUE", requires = "file")]
    answers: Vec<String>,
    /// Record a decision made after the interview, such as the answer to a question from agengo plan --spec, and revise the spec with it.
    #[arg(
        long = "decision",
        value_name = "TEXT",
        requires = "file",
        conflicts_with = "approve"
    )]
    decisions: Vec<String>,
    /// Accept the recommendation for every open question and finish the spec.
    #[arg(long, conflicts_with = "approve")]
    proceed: bool,
    /// Check that the spec is ready and lock it with its digest.
    #[arg(long, requires = "file", conflicts_with = "answers")]
    approve: bool,
    /// How many questions to allow: quick (3 per round, 2 rounds), standard (5, 3) or deep (8, 4). Kept in the spec.
    #[arg(long, value_enum, conflicts_with = "approve")]
    depth: Option<Depth>,
    /// Print the open questions and readiness as JSON.
    #[arg(long)]
    json: bool,
    #[arg(long)]
    agent: Option<String>,
    /// subscription: agents use their CLI login and never see API key variables.
    #[arg(long, value_enum, default_value = "subscription")]
    auth: AuthMode,
    #[arg(long, default_value = "900", value_parser = positive)]
    timeout: u64,
    #[arg(long)]
    roles: Option<PathBuf>,
}

#[derive(Args)]
#[command(group(ArgGroup::new("source").required(true).args(["file", "source_plan", "goal", "spec"])))]
struct Plan {
    #[arg(long)]
    file: Option<PathBuf>,
    /// Draft a plan from an approved spec; its acceptance criteria must cover every requirement of the chosen stories.
    #[arg(long, value_name = "SPEC")]
    spec: Option<PathBuf>,
    /// Stories to plan with --spec: priorities (P1,P2) or story IDs (US-1,US-3). Default: P1.
    #[arg(long, requires = "spec")]
    stories: Option<String>,
    /// Approve the spec first, but only if it is still the version whose approval code agengo spec printed.
    #[arg(long, value_name = "CODE", requires = "spec")]
    approve_spec: Option<String>,
    #[arg(long = "from")]
    source_plan: Option<PathBuf>,
    #[arg(long)]
    goal: Option<String>,
    #[arg(long)]
    context: Option<String>,
    #[arg(long)]
    agent: Option<String>,
    /// subscription: agents use their CLI login and never see API key variables.
    #[arg(long, value_enum, default_value = "subscription")]
    auth: AuthMode,
    #[arg(long, default_value = "900", value_parser = positive)]
    timeout: u64,
    #[arg(long)]
    brief: bool,
    #[arg(long, value_enum, default_value = "json")]
    format: Format,
    #[arg(long)]
    roles: Option<PathBuf>,
}

#[derive(ValueEnum, Clone, Copy)]
enum Depth {
    Quick,
    Standard,
    Deep,
}

#[derive(ValueEnum, Clone)]
enum Format {
    Json,
    Yaml,
}

#[derive(ValueEnum, Clone, Copy, PartialEq)]
enum Choice {
    A,
    B,
    Approve,
    Reject,
}
impl Choice {
    fn name(self) -> &'static str {
        match self {
            Self::A => "A",
            Self::B => "B",
            Self::Approve => "APPROVE",
            Self::Reject => "REJECT",
        }
    }
}

/// How agents authenticate.
#[derive(ValueEnum, Clone, Copy)]
enum AuthMode {
    /// Use the agent CLI's own login and hide API keys from it.
    Subscription,
    /// Pass API key variables through to the agent.
    Api,
}
impl From<AuthMode> for adapter::Auth {
    fn from(mode: AuthMode) -> Self {
        match mode {
            AuthMode::Subscription => Self::Subscription,
            AuthMode::Api => Self::Api,
        }
    }
}

#[derive(ValueEnum, Clone)]
enum Handoff {
    Worktree,
    Commit,
}

#[derive(Args)]
struct Run {
    plan_file: PathBuf,
    #[arg(long)]
    id: Option<String>,
    #[arg(long, default_value = "HEAD")]
    base: String,
    #[arg(long, default_value = "1", value_parser = positive)]
    jobs: u64,
    #[arg(long, default_value = "3", value_parser = positive)]
    review_limit: u64,
    #[arg(long, default_value = "2", value_parser = positive)]
    gate_limit: u64,
    #[arg(long)]
    agent: Option<String>,
    /// subscription: agents use their CLI login and never see API key variables.
    #[arg(long, value_enum, default_value = "subscription")]
    auth: AuthMode,
    #[arg(long, value_enum)]
    builder_handoff: Option<Handoff>,
    #[arg(long, default_value = "900", value_parser = positive)]
    timeout: u64,
    #[arg(long)]
    await_approval: bool,
    #[arg(long)]
    roles: Option<PathBuf>,
}

fn positive(value: &str) -> std::result::Result<u64, String> {
    value
        .parse::<u64>()
        .ok()
        .filter(|value| (1..=i64::MAX as u64).contains(value))
        .ok_or("expected a positive integer".into())
}

/// Exit code 2 means a `--spec` draft holds questions for the user.
fn plan(args: Plan, cwd: &std::path::Path) -> Result<i32> {
    let plan = if let Some(file) = args.file {
        if args.context.is_some() {
            bail!("--context is only available with --goal, --from or --spec");
        }
        contract::load_plan(&file)?.to_value()
    } else {
        let repo = Repo::open(cwd)?;
        let profile = contract::profile(args.roles.as_deref())?;
        let agent = adapter::select(args.agent.as_deref(), &repo.root)?;
        let mut request = json!({"schema_version":1,"role":"plan","context":args.context,
            "principles":spec::principles_or_note(&repo.root)?});
        let mut spec_ref = None;
        let mut memory = None;
        if let Some(path) = &args.spec {
            let mut spec = spec::load(path)?;
            if let Some(code) = &args.approve_spec {
                spec::approve_shown(path, &mut spec, code)?;
            }
            if !spec::approved(&spec) {
                bail!(
                    "{} is not approved or changed after approval; run agengo spec {} --approve first",
                    path.display(),
                    path.display()
                );
            }
            let stories = spec::select_stories(&spec, args.stories.as_deref())?;
            request["goal"] = json!(format!(
                "Implement user stories {} of the approved spec in spec.",
                stories.join(", ")
            ));
            request["spec"] = spec::planning_view(&spec, &stories);
            let stored = spec::stored_path(path, &repo.root)?;
            let drafts = spec::Drafts::new(&repo, &stored, &stories);
            if let Some(previous) = drafts.previous(&spec)? {
                eprintln!("agengo: revising the previous draft with the decisions recorded since");
                request["previous_draft"] = previous;
            }
            memory = Some((drafts, spec["rounds"].clone()));
            spec_ref = Some(json!({"path":stored,
                "digest":spec["approved"]["digest"],"stories":stories}));
        } else if let Some(source) = &args.source_plan {
            let existing = json!(adapter::existing_source(source)?);
            request["existing_plan"] = json!(text(&existing, "existing plan")?);
        } else {
            let goal = json!(args.goal);
            request["goal"] = json!(text(&goal, "goal")?);
        }
        eprintln!(
            "agengo: drafting the plan · {} · timeout {}s",
            adapter::label(agent.as_deref(), args.auth.into()),
            args.timeout
        );
        let invocation = adapter::invoke_measured(
            agent.as_deref(),
            args.auth.into(),
            &request,
            &repo.root,
            args.timeout,
            &profile,
            &config::load(&repo.root)?,
        );
        if let Some(summary) = invocation.usage.as_ref().and_then(usage::describe_call) {
            eprintln!("agengo: plan drafting used {summary}");
        }
        let draft = invocation.reply?;
        contract::validate_version(&draft)?;
        if let Some(questions) = draft.get("questions") {
            if !questions.is_array() {
                bail!("questions must be a list");
            }
            for question in array_or_empty(questions) {
                text(question, "questions")?;
            }
        }
        let mut draft = draft;
        settle_acceptance(&mut draft, spec_ref.is_some());
        if let Some(reference) = spec_ref {
            draft["spec"] = reference;
        }
        // A draft that still asks is kept, so the next draft revises it
        // instead of starting over; a complete one ends the exchange.
        let complete = array_or_empty(&draft["questions"]).is_empty();
        let draft = if complete {
            contract::validate_plan(draft)?
        } else {
            draft
        };
        if let Some((drafts, round)) = memory {
            let kept = if complete {
                drafts.forget()
            } else {
                drafts.remember(&draft, &round)
            };
            if let Err(error) = kept {
                eprintln!("agengo: warning: cannot keep the draft for the next one: {error:#}");
            }
        }
        draft
    };
    if array_or_empty(&plan["questions"]).is_empty() && plan.get("spec").is_some() {
        let typed = plan::Plan::from_value(plan.clone())?;
        let repo = Repo::open(cwd)?;
        if let Some((_, warnings)) = spec::coverage(&typed, &repo.root)? {
            for warning in warnings {
                eprintln!("agengo: warning: {warning}");
            }
        }
    }
    let guidance = args
        .spec
        .as_deref()
        .filter(|_| !array_or_empty(&plan["questions"]).is_empty())
        .map(|path| {
            spec_questions(
                array_or_empty(&plan["questions"]),
                path,
                args.stories.as_deref(),
            )
        });
    if args.brief {
        let questions = array_or_empty(&plan["questions"]);
        let title = plan["goal"]
            .as_str()
            .or(args.goal.as_deref())
            .map(str::to_owned)
            .or_else(|| {
                args.source_plan
                    .as_ref()
                    .map(|source| source.display().to_string())
            })
            .unwrap_or_else(|| "Plan".into());
        let response = if args.spec.is_some() {
            "Record each answer in the spec with agengo spec --decision, show the user what it changed, then approve that version and draft the plan again with agengo plan --spec --approve-spec <code>."
        } else {
            "Answer the questions and draft the plan again with --context."
        };
        let (kind, detail) = if questions.is_empty() {
            (
                "approval",
                json!({"situation":format!("{} with scopes and acceptance checks{}.",count(array_or_empty(&plan["tasks"]).len(),"task"),
                    match notable_assumptions(&plan).len() {
                        0 => String::new(),
                        n => format!("; {} to confirm", count(n, "assumption")),
                    }),
                "recommendation":"Approve if the plan matches the goal and scope.",
                "reason":"agengo run executes the plan's tasks and check commands.",
                "response":"Approve by passing the YAML or JSON plan to agengo run, or edit the plan first.",
                "commands":plan::Plan::from_value(plan.clone()).map(|plan| plan.command_lines()).unwrap_or_default()}),
            )
        } else {
            (
                "information",
                json!({"situation":format!("Needs clarification: {}",questions.iter().map(string_or_empty).collect::<Vec<_>>().join(" ")),
                "response":response}),
            )
        };
        let message =
            json!({"kind":kind,"run_id":"PLAN","title":title,"detail":detail.to_string()});
        // This draft has no persisted request code.
        show(&message)?;
        for task in array_or_empty(&plan["tasks"])
            .iter()
            .filter(|_| questions.is_empty())
        {
            println!(
                "- {} · {}",
                string_or_empty(&task["id"]),
                task["title"]
                    .as_str()
                    .unwrap_or_else(|| string_or_empty(&task["goal"]))
            );
        }
        for assumption in notable_assumptions(&plan) {
            println!(
                "- Assumed [{}]: {} (if wrong: {})",
                string_or_empty(&assumption["impact"]),
                string_or_empty(&assumption["text"]),
                string_or_empty(&assumption["if_wrong"])
            );
        }
    } else {
        match args.format {
            Format::Yaml => {
                let mut document = plan;
                document["schema_version"] = json!(1);
                print!("{}", serde_yaml_ng::to_string(&document)?);
            }
            Format::Json => println!("{}", serde_json::to_string_pretty(&plan)?),
        }
    }
    if let Some(guidance) = guidance {
        eprint!("{guidance}");
        return Ok(2);
    }
    Ok(0)
}

/// What to do with the questions in a draft from a spec: the answers are
/// decisions about the product, so they go into the spec, which stays the
/// single record of what the user decided.
fn spec_questions(questions: &[Value], spec: &std::path::Path, stories: Option<&str>) -> String {
    let spec = spec.display();
    let mut text = format!(
        "agengo: the planner needs {} before this plan can run:
",
        count(questions.len(), "answer")
    );
    for (index, question) in questions.iter().enumerate() {
        text += &format!(
            "  {}. {}
",
            index + 1,
            string_or_empty(question)
        );
    }
    let stories = stories.map_or(String::new(), |stories| format!(" --stories {stories}"));
    text += &format!(
        "Next: record each answer in the spec; agengo shows what it changed and an approval code:
           agengo spec {spec} --decision \"<question and answer in one sentence>\"
         Once the user has reviewed those changes, approve that version and draft the plan again,
         which revises this draft instead of starting over:
           agengo plan --spec {spec}{stories} --approve-spec <code>
         An answer that changes nothing the user gets can instead go to this command with --context \"<answer>\".
"
    );
    text
}

/// The planner's high and medium assumptions, high first: the guesses the
/// person approving the plan should confirm.
fn notable_assumptions(plan: &Value) -> Vec<&Value> {
    ["high", "medium"]
        .iter()
        .flat_map(|impact| {
            array_or_empty(&plan["assumptions"])
                .iter()
                .filter(move |item| item["impact"] == *impact)
        })
        .collect()
}

/// The planner returns acceptance criteria as `{id, text, refs}`. Without a
/// spec, refs mean nothing, so criteria with the default ID go back to plain
/// text; with one, empty refs are dropped and the coverage gate reports them.
fn settle_acceptance(draft: &mut Value, with_spec: bool) {
    let Some(tasks) = draft["tasks"].as_array_mut() else {
        return;
    };
    for task in tasks {
        let Some(criteria) = task["acceptance"].as_array_mut() else {
            continue;
        };
        for (index, criterion) in criteria.iter_mut().enumerate() {
            let Some(fields) = criterion.as_object_mut() else {
                continue;
            };
            let empty = fields
                .get("refs")
                .and_then(Value::as_array)
                .is_none_or(Vec::is_empty);
            if !with_spec || empty {
                fields.remove("refs");
            }
            if !with_spec
                && fields.len() == 2
                && fields.get("id").and_then(Value::as_str) == Some(&format!("AC-{}", index + 1))
            {
                *criterion = fields.get("text").cloned().unwrap_or(Value::Null);
            }
        }
    }
}

/// Checks a plan's spec coverage and prints the warnings; returns the spec to
/// keep with the run.
fn checked_spec(plan: &plan::Plan, repo: &Repo) -> Result<Option<Value>> {
    Ok(spec::coverage(plan, &repo.root)?.map(|(spec, warnings)| {
        for warning in warnings {
            eprintln!("agengo: warning: {warning}");
        }
        spec
    }))
}

/// The run ID a plan file names: its file name without the extension, for a
/// plan kept in `.agengo/plans/` whose name is a valid run ID
/// (`.agengo/plans/p1-admin.yaml` → `p1-admin`). Plans elsewhere, such as a
/// reused `plan.yaml`, keep getting a generated ID.
fn run_id_from(plan_file: &std::path::Path) -> Option<String> {
    if !plan_file
        .parent()?
        .ends_with(std::path::Path::new(init::PLANS_DIR))
    {
        return None;
    }
    let stem = plan_file.file_stem()?.to_str()?;
    identifier(stem, "run id").ok()?;
    Some(stem.to_owned())
}

fn start(repo: &Repo, args: Run) -> Result<bool> {
    let plan = contract::load_plan(&args.plan_file)?;
    let spec_body = checked_spec(&plan, repo)?;
    let profile = contract::profile(args.roles.as_deref())?;
    let agent = adapter::select(args.agent.as_deref(), &repo.root)?;
    agent_check::warn_if_unchecked(&repo.data, agent.as_deref());
    let mode = match args.builder_handoff {
        Some(Handoff::Commit) => "commit",
        Some(Handoff::Worktree) => "worktree",
        None => agent.as_deref().map_or("worktree", driver::default_handoff),
    };
    // Without --id the run is named after the plan file, so the plan, the
    // branch agengo/<run-id> and the reports share one name.
    let named = args.id.is_none();
    let id = args
        .id
        .or_else(|| run_id_from(&args.plan_file))
        .unwrap_or_else(|| engine::id()[..12].to_owned());
    identifier(&id, "run id")?;
    let _lock = store::lock(&repo.data, &id)?;
    let store = Store::open(&repo.data)?;
    if store
        .one("SELECT 1 FROM runs WHERE id=?", &[&id])?
        .is_some()
    {
        if named {
            bail!(
                "run already exists: {id} (named after the plan file); use agengo resume {id}, or pass --id for a new run"
            );
        }
        bail!("run already exists: {id}; use resume");
    }
    if repo.current(&engine::reference(&id))?.is_some() {
        if named {
            bail!(
                "integration branch already exists: agengo/{id} (the run is named after the plan file); pass --id for another name"
            );
        }
        bail!("integration branch already exists: agengo/{id}");
    }
    if repo.current("HEAD")?.is_none() {
        bail!("this repository has no commits yet; run `git add -A && git commit -m \"Initial commit\"` so agengo has a base to build on");
    }
    let base = repo.sha(&args.base)?;
    if matches!(args.auth, AuthMode::Subscription)
        && std::env::var_os("ANTHROPIC_API_KEY").is_some()
    {
        eprintln!("agengo: note: ANTHROPIC_API_KEY is set but agengo removes it for agents (--auth subscription); pass --auth api to bill the key instead.");
    }
    let pending = repo.git(&["status", "--porcelain"])?;
    if !pending.is_empty() {
        eprintln!(
            "agengo: warning: {} file(s) are not committed. Agents build from {}, so they will not see those changes; commit them first if the run needs them.",
            pending.lines().count(),
            args.base
        );
    }
    let preflight = plan.preflight(&repo.root, &platform::detect(), &|program, base| {
        process::resolve(program, base)
    });
    for warning in &preflight.warnings {
        eprintln!("agengo: warning: {warning}");
    }
    for warning in
        plan.ignored_program_warnings(&|path| repo.git(&["check-ignore", "-q", "--", path]).is_ok())
    {
        eprintln!("agengo: warning: {warning}");
    }
    if !preflight.errors.is_empty() {
        bail!(
            "the plan cannot run here:\n- {}",
            preflight.errors.join("\n- ")
        );
    }
    // SQLite integers are signed 64-bit.
    let jobs = i64::try_from(args.jobs).context("--jobs is too large")?;
    let timeout = i64::try_from(args.timeout).context("--timeout is too large")?;
    let review_limit = i64::try_from(args.review_limit).context("--review-limit is too large")?;
    let gate_limit = i64::try_from(args.gate_limit).context("--gate-limit is too large")?;
    eprintln!(
        "agengo: run {id} · {} · handoff {mode} · jobs {jobs} · review limit {review_limit} · gate limit {gate_limit} · timeout {timeout}s per attempt{}",
        adapter::label(agent.as_deref(), args.auth.into()),
        if args.await_approval {
            " · waits for plan approval"
        } else {
            ""
        }
    );
    let notice = store.atomic(|| {
        store.0.execute("INSERT INTO runs (id,base,tip,state,jobs,agent,timeout,review_limit,gate_limit) VALUES (?,?,?,?,?,?,?,?,?)",
            params![id,base,base,if args.await_approval {"awaiting_approval"} else {"running"},jobs,agent,timeout,review_limit,gate_limit])?;
        store.0.execute("INSERT INTO plans VALUES (?,1,?)",params![id,plan.to_value().to_string()])?;
        store.0.execute("INSERT INTO run_handoff VALUES (?,?)",params![id,mode])?;
        store.0.execute("INSERT INTO run_auth VALUES (?,?)",params![id,adapter::Auth::from(args.auth).as_str()])?;
        store.0.execute("INSERT INTO run_role_profiles VALUES (?,?)",params![id,profile.to_string()])?;
        spec::keep_with_run(&store,&id,&plan,spec_body.as_ref())?;
        for task in &plan.tasks {
            store.0.execute("INSERT INTO tasks (run_id,id) VALUES (?,?)",params![id,task.id])?;
        }
        let tasks = plan.tasks.len();
        if args.await_approval {
            store.notice(&id,None,"approval",&plan.goal,json!({
                "situation":format!("Plan v1 has {}, starting from commit {base}.",count(tasks,"task")),
                "recommendation":"Approve after confirming the scopes and acceptance criteria.",
                "reason":"The run executes the tasks and check commands in this version.",
                "response":"Approve or reject the plan.","impact":"The run waits for approval before the first dispatch.",
                "commands":plan.command_lines()
            }),Some(json!({"phase":"plan","head":base})))?;
            Ok(None)
        } else {
            Ok(Some(store.notice(&id,None,"progress",&plan.goal,json!({
                "situation":format!("Starting plan v1 with {} from commit {base}.",count(tasks,"task"))}),None)?))
        }
    })?;
    if let Some(notice) = notice {
        show(&notice)?;
    }
    engine::Engine::new(repo, &store, &id)?.execute()
}

fn execution(cli: Cli) -> Result<i32> {
    if let Command::Spec(args) = cli.command {
        return spec::execute(
            &cli.repo,
            spec::Command {
                idea: args.idea,
                path: args.file,
                output: args.output,
                force: args.force,
                answers: args.answers,
                decisions: args.decisions,
                proceed: args.proceed,
                approve: args.approve,
                depth: args.depth.map(|depth| {
                    match depth {
                        Depth::Quick => "quick",
                        Depth::Standard => "standard",
                        Depth::Deep => "deep",
                    }
                    .to_owned()
                }),
                json: args.json,
                agent: args.agent,
                auth: args.auth.into(),
                timeout: args.timeout,
                roles: args.roles,
            },
        );
    }
    if let Command::Plan(args) = cli.command {
        return plan(args, &cli.repo);
    }
    if let Command::Doctor { json } = cli.command {
        return Ok(if doctor::report(&cli.repo, json)? {
            0
        } else {
            1
        });
    }
    if let Command::Setup { apply } = cli.command {
        setup::run_setup(&cli.repo, apply)?;
        return Ok(0);
    }
    if let Command::Agent { action } = cli.command {
        let repo = Repo::open(&cli.repo)?;
        match action {
            None => driver::show(&repo.root)?,
            Some(AgentAction::Check { name }) => {
                let passed = agent_check::run_check(&repo.root, &repo.data, name.as_deref())?;
                return Ok(i32::from(!passed));
            }
            Some(AgentAction::Use { name }) => {
                driver::use_agent(&repo.root, &name)?;
                if name != "auto" && repo.data.join("state.sqlite3").exists() {
                    let store = store::Store::open(&repo.data)?;
                    let runs: Vec<(String, Option<String>)> = store
                        .rows("SELECT id, agent FROM runs WHERE state <> 'done'", &[])?
                        .iter()
                        .filter_map(|run| {
                            Some((
                                run["id"].as_str()?.to_owned(),
                                run["agent"].as_str().map(str::to_owned),
                            ))
                        })
                        .collect();
                    if let Some(note) = driver::pinned_runs_note(&runs, &name) {
                        eprintln!("{note}");
                    }
                }
            }
        }
        return Ok(0);
    }
    if let Command::Config { action } = cli.command {
        let repo = Repo::open(&cli.repo)?;
        match action {
            None => {
                for line in config::describe(&repo.root)? {
                    println!("{line}");
                }
            }
            Some(ConfigAction::Set { key, value }) => {
                config::set(&repo.root, &key, Some(&value))?;
                println!("agengo: {key} = {value} ({})", config::PATH);
            }
            Some(ConfigAction::Unset { key }) => {
                config::set(&repo.root, &key, None)?;
                println!("agengo: {key} removed from {}", config::PATH);
            }
        }
        return Ok(0);
    }
    if let Command::Init { no_agents_md } = cli.command {
        let output = process::run(
            std::process::Command::new("git")
                .current_dir(&cli.repo)
                .args(["rev-parse", "--show-toplevel"]),
            None,
            None,
        )?;
        if !output.status.success() {
            bail!("agengo init must run inside a Git repository; run `git init` and make a first commit, then try again (`agengo doctor` checks the rest)");
        }
        let root = PathBuf::from(String::from_utf8(output.stdout)?.trim_end_matches('\n'));
        init::report(&root, &init::install(&root, !no_agents_md)?);
        return Ok(0);
    }
    if let Command::Roles { file } = cli.command {
        let roles = contract::profile(file.as_deref())?;
        let mut summary = json!({"schema_version":roles["schema_version"],"roles":{}});
        for (name, role) in roles["roles"]
            .as_object()
            .context("the roles profile has no roles table")?
        {
            summary["roles"][name] =
                json!({"purpose":role["purpose"],"file_access":role["file_access"]});
        }
        print!("{}", serde_yaml_ng::to_string(&summary)?);
        return Ok(0);
    }
    let repo = Repo::open(&cli.repo)?;
    handoff::migrate_legacy_refs(&repo)?;
    if let Command::Run(args) = cli.command {
        return Ok(if start(&repo, args)? { 0 } else { 2 });
    }
    if let Command::Metrics {
        run_id: None, json, ..
    } = cli.command
    {
        let store = Store::open(&repo.data)?;
        let transaction = store.0.unchecked_transaction()?;
        metrics::show_all(&store, json)?;
        transaction.commit()?;
        return Ok(0);
    }
    let id = match &cli.command {
        Command::Status { run_id, .. }
        | Command::Inbox { run_id, .. }
        | Command::Metrics {
            run_id: Some(run_id),
            ..
        }
        | Command::Resume { run_id, .. }
        | Command::Pause { run_id, .. }
        | Command::Resolve { run_id, .. }
        | Command::Respond { run_id, .. }
        | Command::Amend { run_id, .. }
        | Command::Clean { run_id } => run_id,
        _ => unreachable!(),
    };
    identifier(id, "run id")?;
    let store = Store::open(&repo.data)?;
    match cli.command {
        Command::Status {
            watch: true,
            interval,
            ..
        } => {
            drop(store);
            control::watch(&repo, id, interval)?;
        }
        Command::Status { json, .. } => {
            let transaction = store.0.unchecked_transaction()?;
            control::status(&repo, &store, id, json)?;
            transaction.commit()?;
        }
        Command::Inbox { json, .. } | Command::Metrics { json, .. } => {
            let transaction = store.0.unchecked_transaction()?;
            if matches!(cli.command, Command::Inbox { .. }) {
                inbox::view(&store, &repo.data, id, json)?;
            } else {
                metrics::show(&store, id, json)?;
            }
            transaction.commit()?;
        }
        Command::Resume {
            task: None,
            ref agent,
            ..
        } => {
            let _lock = store::lock(&repo.data, id)?;
            let stored = store.run(id)?["agent"].as_str().map(str::to_owned);
            if let Some(flag) = agent {
                let chosen = adapter::select(Some(flag), &repo.root)?;
                store.0.execute(
                    "UPDATE runs SET agent=? WHERE id=?",
                    rusqlite::params![chosen, id],
                )?;
                eprintln!(
                    "agengo: run {id} continues with {}",
                    adapter::label(chosen.as_deref(), adapter::Auth::Subscription)
                        .trim_start_matches("agent ")
                );
            } else if let Err(error) = adapter::executable(stored.as_deref()) {
                bail!("{error:#}\nThis run started with an agent that is not available now; continue with another one: agengo resume {id} --agent NAME (see `agengo agent`)");
            } else if let Ok(driver::Selection::Chosen { name, .. }) =
                driver::selection(None, &repo.root)
            {
                if let Some(note) = driver::resume_note(id, stored.as_deref(), &name) {
                    eprintln!("{note}");
                }
            }
            return Ok(if engine::Engine::new(&repo, &store, id)?.execute()? {
                0
            } else {
                2
            });
        }
        Command::Resume {
            task: Some(ref task),
            ..
        }
        | Command::Pause { ref task, .. } => {
            identifier(task, "task id")?;
            let paused = matches!(cli.command, Command::Pause { .. });
            let notice = store.atomic(|| control::pause(&store, id, task, paused))?;
            show(&notice)?;
        }
        Command::Resolve {
            ref task_id,
            ref note,
            ..
        } => {
            identifier(task_id, "task id")?;
            let _lock = store::lock(&repo.data, id)?;
            let notice = store
                .atomic(|| control::resolve_command(&store, &store.run(id)?, task_id, note))?;
            show(&notice)?;
        }
        Command::Respond {
            ref code,
            choice,
            ref note,
            ref plan,
            ..
        } => {
            let _lock = if choice == Some(Choice::B) {
                Some(store::lock(&repo.data, id)?)
            } else {
                None
            };
            let replacement = plan.as_deref().map(contract::load_plan).transpose()?;
            let spec_body = match &replacement {
                Some(plan) => checked_spec(plan, &repo)?,
                None => None,
            };
            let notice = store.atomic(|| {
                let notice = control::respond(
                    &store,
                    id,
                    code,
                    choice.map(Choice::name),
                    note.as_deref(),
                    replacement.as_ref(),
                )?;
                if let Some(plan) = &replacement {
                    spec::keep_with_run(&store, id, plan, spec_body.as_ref())?;
                }
                Ok(notice)
            })?;
            show(&notice)?;
        }
        Command::Clean { .. } => {
            let _lock = store::lock(&repo.data, id)?;
            let delivered = store.run(id)?["state"] == "done";
            println!("[CLEANUP] {id}");
            println!("- {}", engine::cleanup(&repo, id, delivered)?);
            if !delivered {
                println!("- The run is not delivered, so its agengo-work/{id}/* branches and candidate refs are kept; resume creates new worktrees as needed.");
            }
        }
        Command::Amend {
            ref plan_file,
            ref note,
            ..
        } => {
            let _lock = store::lock(&repo.data, id)?;
            text(&Value::String(note.clone()), "decision note")?;
            let replacement = contract::load_plan(plan_file)?;
            let spec_body = checked_spec(&replacement, &repo)?;
            let notice = store.atomic(|| {
                let notice = control::amend(&store, &store.run(id)?, &replacement, note, None)?;
                spec::keep_with_run(&store, id, &replacement, spec_body.as_ref())?;
                Ok(notice)
            })?;
            show(&notice)?;
        }
        _ => unreachable!(),
    }
    Ok(0)
}

/// Whether a panic came from printing to a closed stdout or stderr, as when
/// output is piped into `head`.
fn closed_output(message: &str) -> bool {
    message.starts_with("failed printing to stdout")
        || message.starts_with("failed printing to stderr")
}

/// Exit quietly when the reader of agengo's output went away, instead of
/// printing a panic. 141 is the status shells report for a closed pipe. Any
/// open transaction rolls back, and an interrupted run continues with resume.
fn quiet_closed_output() {
    let default = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let payload = info.payload();
        let message = payload
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| payload.downcast_ref::<&str>().copied())
            .unwrap_or_default();
        if closed_output(message) {
            std::process::exit(141);
        }
        default(info);
    }));
}

fn main() {
    quiet_closed_output();
    let cli = Cli::parse();
    if let Some(mode) = cli.sandbox {
        config::override_sandbox(mode);
    }
    let result = ctrlc::set_handler(|| INTERRUPTED.store(true, Ordering::Relaxed))
        .map_err(anyhow::Error::from)
        .and_then(|()| execution(cli));
    let code = if INTERRUPTED.load(Ordering::Relaxed) {
        eprintln!("Run interrupted. Use status or resume with the same run ID.");
        130
    } else {
        match result {
            Ok(code) => code,
            Err(error) => {
                eprintln!("agengo: {error:#}");
                1
            }
        }
    };
    std::process::exit(code);
}

#[cfg(test)]
mod tests {
    use super::{closed_output, run_id_from};
    use std::path::Path;

    #[test]
    fn a_plan_file_names_its_run() {
        assert_eq!(
            run_id_from(Path::new(".agengo/plans/p1-admin.yaml")).as_deref(),
            Some("p1-admin")
        );
        assert_eq!(
            run_id_from(Path::new("/work/repo/.agengo/plans/fix_login.json")).as_deref(),
            Some("fix_login")
        );
        // Plans elsewhere, and names that are not valid run IDs, leave the
        // ID to agengo.
        assert_eq!(run_id_from(Path::new("plan.yaml")), None);
        assert_eq!(run_id_from(Path::new("plans/p1-admin.yaml")), None);
        assert_eq!(run_id_from(Path::new(".agengo/plans/old/p1.yaml")), None);
        assert_eq!(run_id_from(Path::new(".agengo/plans/plan v2.yaml")), None);
        assert_eq!(run_id_from(Path::new(".agengo/plans/.yaml")), None);
    }

    #[test]
    fn only_printing_to_a_closed_stream_exits_quietly() {
        assert!(closed_output(
            "failed printing to stdout: Broken pipe (os error 32)"
        ));
        assert!(closed_output(
            "failed printing to stderr: The pipe is being closed. (os error 232)"
        ));
        assert!(!closed_output("index out of bounds"));
    }
}