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 {
Spec(Spec),
Plan(Plan),
Run(Run),
Resume {
run_id: String,
#[arg(long)]
task: Option<String>,
},
Status {
run_id: String,
#[arg(long)]
json: bool,
},
Inbox {
run_id: String,
#[arg(long)]
json: bool,
},
#[command(group(ArgGroup::new("target").required(true).args(["run_id", "all"])))]
Metrics {
run_id: Option<String>,
#[arg(long)]
all: bool,
#[arg(long)]
json: bool,
},
Resolve {
run_id: String,
task_id: String,
#[arg(long)]
note: String,
},
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 {
run_id: String,
#[arg(long)]
task: String,
},
Amend {
run_id: String,
plan_file: PathBuf,
#[arg(long)]
note: String,
},
Clean { run_id: String },
Init {
#[arg(long)]
no_agents_md: bool,
},
Roles {
#[arg(long)]
file: Option<PathBuf>,
},
}
#[derive(Args)]
#[command(group(ArgGroup::new("source").required(true).args(["idea", "file"])))]
struct Spec {
#[arg(long)]
idea: Option<String>,
file: Option<PathBuf>,
#[arg(short, long, requires = "idea", value_name = "PATH")]
output: Option<PathBuf>,
#[arg(long, requires = "idea")]
force: bool,
#[arg(long = "answer", value_name = "Q-n=VALUE", requires = "file")]
answers: Vec<String>,
#[arg(
long = "decision",
value_name = "TEXT",
requires = "file",
conflicts_with = "approve"
)]
decisions: Vec<String>,
#[arg(long, conflicts_with = "approve")]
proceed: bool,
#[arg(long, requires = "file", conflicts_with = "answers")]
approve: bool,
#[arg(long, value_enum, conflicts_with = "approve")]
depth: Option<Depth>,
#[arg(long)]
json: bool,
#[arg(long)]
agent: Option<String>,
#[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>,
#[arg(long, value_name = "SPEC")]
spec: Option<PathBuf>,
#[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>,
#[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",
}
}
}
#[derive(ValueEnum, Clone, Copy)]
enum AuthMode {
Subscription,
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>,
#[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())
}
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()});
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)
}
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
}
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()
}
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);
}
}
}
}
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)?;
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(¬ice)?;
}
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(¬ice)?;
}
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(¬ice)?;
}
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(¬ice)?;
}
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(¬ice)?;
}
_ => unreachable!(),
}
Ok(0)
}
fn closed_output(message: &str) -> bool {
message.starts_with("failed printing to stdout")
|| message.starts_with("failed printing to stderr")
}
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"));
}
}