agengo 0.4.0

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
mod adapter;
mod agent;
mod context;
mod contract;
mod control;
mod engine;
mod failure;
mod handoff;
mod inbox;
mod init;
mod integrity;
mod metrics;
mod plan;
mod process;
mod quality;
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,
    #[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>,
    },
    /// Show plan, tasks and evidence.
    Status {
        run_id: String,
        #[arg(long)]
        json: bool,
    },
    /// 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,
    },
    /// Validate a YAML role catalog and its prompt references.
    Roles {
        #[arg(long)]
        file: Option<PathBuf>,
    },
}

#[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: 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>,
    #[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::executable(args.agent.as_deref())?;
        let mut request = json!({"schema_version":1,"role":"plan","context":args.context,
            "principles":spec::principles(&repo.root)?});
        let mut spec_ref = None;
        if let Some(path) = &args.spec {
            let spec = spec::load(path)?;
            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);
            spec_ref = Some(json!({"path":spec::stored_path(path, &repo.root)?,
                "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")?);
        }
        let invocation = adapter::invoke_measured(
            agent.as_deref(),
            args.auth.into(),
            &request,
            &repo.root,
            args.timeout,
            &profile,
        );
        if let Some(summary) = invocation.usage.as_ref().and_then(usage::describe) {
            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;
        }
        if array_or_empty(&draft["questions"]).is_empty() {
            contract::validate_plan(draft)?
        } else {
            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, approve it again and draft the plan again."
        } 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."}),
            )
        } 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, approve it again and draft the plan again:
           agengo spec {spec} --decision \"<question and answer in one sentence>\"
           agengo spec {spec} --approve
           agengo plan --spec {spec}{stories}
         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
    }))
}

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::executable(args.agent.as_deref())?;
    let mode = match args.builder_handoff {
        Some(Handoff::Commit) => "commit",
        Some(Handoff::Worktree) => "worktree",
        None if agent.is_some() => "commit",
        None => "worktree",
    };
    let id = args.id.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()
    {
        bail!("run already exists: {id}; use resume");
    }
    if repo.current(&engine::reference(&id))?.is_some() {
        bail!("integration branch already exists: af/{id}");
    }
    let base = repo.sha(&args.base)?;
    // 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")?;
    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."
            }),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::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");
        }
        let root = PathBuf::from(String::from_utf8(output.stdout)?.trim_end_matches('\n'));
        init::report(&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().unwrap() {
            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 { 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, id, json)?;
            } else {
                metrics::show(&store, id, json)?;
            }
            transaction.commit()?;
        }
        Command::Resume { task: None, .. } => {
            let _lock = store::lock(&repo.data, id)?;
            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 af-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();
    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;

    #[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"));
    }
}