mod adapter;
mod context;
mod contract;
mod control;
mod engine;
mod failure;
mod handoff;
mod inbox;
mod metrics;
mod process;
mod quality;
mod store;
mod usage;
use anyhow::{bail, 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 {
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,
},
Metrics {
run_id: String,
#[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 },
Roles {
#[arg(long)]
file: Option<PathBuf>,
},
}
#[derive(Args)]
#[command(group(ArgGroup::new("source").required(true).args(["file", "source_plan", "goal"])))]
struct Plan {
#[arg(long)]
file: Option<PathBuf>,
#[arg(long = "from")]
source_plan: Option<PathBuf>,
#[arg(long)]
goal: Option<String>,
#[arg(long)]
context: Option<String>,
#[arg(long)]
agent: Option<String>,
#[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)]
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)]
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)]
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<()> {
let plan = if let Some(file) = args.file {
if args.context.is_some() {
bail!("--context is only available with --goal or --from");
}
contract::load_plan(&file)?
} 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});
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(),
&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")?;
}
}
if array_or_empty(&draft["questions"]).is_empty() {
contract::validate_plan(draft)?
} else {
draft
}
};
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 (kind, detail) = if questions.is_empty() {
(
"approval",
json!({"situation":format!("{} with scopes and acceptance checks.",count(array_or_empty(&plan["tasks"]).len(),"task")),
"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":"Answer the questions and draft the plan again with --context."}),
)
};
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"]),
engine::title(task)
);
}
} 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)?),
}
}
Ok(())
}
fn start(repo: &Repo, args: Run) -> Result<bool> {
let plan = contract::load_plan(&args.plan_file)?;
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 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"},args.jobs,agent,args.timeout,args.review_limit,args.gate_limit])?;
store.0.execute("INSERT INTO plans VALUES (?,1,?)",params![id,plan.to_string()])?;
store.0.execute("INSERT INTO run_handoff VALUES (?,?)",params![id,mode])?;
store.0.execute("INSERT INTO run_role_profiles VALUES (?,?)",params![id,profile.to_string()])?;
for task in array_or_empty(&plan["tasks"]) {
store.0.execute("INSERT INTO tasks (run_id,id) VALUES (?,?)",params![id,string_or_empty(&task["id"])])?;
}
let tasks = array_or_empty(&plan["tasks"]).len();
if args.await_approval {
store.notice(&id,None,"approval",string_or_empty(&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",string_or_empty(&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::Plan(args) = cli.command {
plan(args, &cli.repo)?;
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)?;
if let Command::Run(args) = cli.command {
return Ok(if start(&repo, args)? { 0 } else { 2 });
}
let id = match &cli.command {
Command::Status { run_id, .. }
| Command::Inbox { run_id, .. }
| Command::Metrics { 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 notice = store.atomic(|| {
control::respond(
&store,
id,
code,
choice.map(Choice::name),
note.as_deref(),
replacement.as_ref(),
)
})?;
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 notice = store
.atomic(|| control::amend(&store, &store.run(id)?, &replacement, note, None))?;
show(¬ice)?;
}
_ => unreachable!(),
}
Ok(0)
}
fn main() {
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);
}