mod drafts;
mod plan_link;
#[cfg(test)]
mod tests;
mod validate;
pub use drafts::*;
pub use plan_link::*;
use validate::*;
use crate::{
adapter,
contract::{self, array_or_empty, string_or_empty, text},
plan::{Plan, Task},
process::Repo,
store::Store,
};
use anyhow::{bail, Context, Result};
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeSet,
fs,
io::Write,
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
pub const DEPTHS: [(&str, usize, u64); 3] = [("quick", 3, 2), ("standard", 5, 3), ("deep", 8, 4)];
pub const DEFAULT_DEPTH: &str = "standard";
pub const MAX_OPTIONS: usize = 4;
const DECISION: &str = "Decision made after the interview";
const CATEGORIES: [&str; 10] = [
"scope",
"actors",
"quality",
"flow",
"data",
"integration",
"edge_cases",
"constraints",
"completion",
"terminology",
];
const IMPACTS: [&str; 3] = ["high", "medium", "low"];
const PRIORITIES: [&str; 3] = ["P1", "P2", "P3"];
const SOURCES: [&str; 3] = ["option", "recommended", "free"];
const BODY: [&str; 9] = [
"problem",
"actors",
"stories",
"requirements",
"success_criteria",
"out_of_scope",
"constraints",
"assumptions",
"feasibility",
];
const SESSION: [&str; 8] = [
"schema_version",
"idea",
"questions",
"clarifications",
"depth",
"rounds",
"questions_issued",
"approved",
];
const KEY_ORDER: [&str; 38] = [
"schema_version",
"idea",
"problem",
"actors",
"stories",
"requirements",
"success_criteria",
"out_of_scope",
"constraints",
"assumptions",
"feasibility",
"questions",
"clarifications",
"depth",
"rounds",
"questions_issued",
"approved",
"round",
"id",
"priority",
"story",
"category",
"impact",
"key",
"label",
"title",
"question",
"text",
"why",
"answer",
"source",
"implication",
"if_wrong",
"options",
"recommended",
"scenarios",
"digest",
"at",
];
pub struct Command {
pub idea: Option<String>,
pub path: Option<PathBuf>,
pub output: Option<PathBuf>,
pub force: bool,
pub answers: Vec<String>,
pub decisions: Vec<String>,
pub proceed: bool,
pub approve: bool,
pub depth: Option<String>,
pub json: bool,
pub agent: Option<String>,
pub auth: adapter::Auth,
pub timeout: u64,
pub roles: Option<PathBuf>,
}
pub const PRINCIPLES_PATH: &str = ".agengo/principles.md";
pub const SPEC_PATH: &str = ".agengo/spec.yaml";
const PRINCIPLES_LIMIT: usize = 32 * 1024;
pub fn principles_or_note(root: &Path) -> Result<Option<String>> {
let found = principles(root)?;
if found.is_none() {
eprintln!(
"agengo: note: no project principles ({PRINCIPLES_PATH} is missing or empty), so the agent will infer your stack and commands. Run `agengo init` if it is missing, then fill it in."
);
}
Ok(found)
}
pub fn principles(root: &Path) -> Result<Option<String>> {
let path = root.join(PRINCIPLES_PATH);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error).with_context(|| format!("cannot read {}", path.display())),
};
let mut kept = String::new();
let mut rest = text.as_str();
while let Some(start) = rest.find("<!--") {
kept.push_str(&rest[..start]);
rest = rest[start..]
.find("-->")
.map_or("", |end| &rest[start + end + 3..]);
}
kept.push_str(rest);
let kept: String = kept
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
let filled = kept
.lines()
.any(|line| !line.trim().is_empty() && !line.trim_start().starts_with('#'));
if !filled {
return Ok(None);
}
if kept.len() > PRINCIPLES_LIMIT {
bail!(
"{} is longer than {} KiB; keep it to the rules agents need",
path.display(),
PRINCIPLES_LIMIT / 1024
);
}
Ok(Some(kept.trim().to_owned()))
}
pub fn execute(cwd: &Path, command: Command) -> Result<i32> {
let (mut spec, path, fresh) = match (&command.idea, &command.path) {
(Some(idea), None) => {
let path = command
.output
.clone()
.unwrap_or_else(|| PathBuf::from(SPEC_PATH));
if path.exists() && !command.force {
bail!(
"{} already exists; pass --force to replace it",
path.display()
);
}
let idea = json!(idea);
(empty(text(&idea, "idea")?), path, true)
}
(None, Some(path)) => (load(path)?, path.clone(), false),
_ => bail!("pass either --idea or a spec file"),
};
let mut changed = false;
if let Some(depth) = &command.depth {
if !DEPTHS.iter().any(|(name, ..)| name == depth) {
bail!("unknown depth {depth}; use quick, standard or deep");
}
changed = spec["depth"] != json!(depth);
spec["depth"] = json!(depth);
}
if command.approve {
lock(&path, &mut spec)?;
report(&spec, &path, None, command.json)?;
return Ok(0);
}
let before = (!fresh).then(|| spec.clone());
let mut answers = apply_answers(&mut spec, &command.answers, command.proceed)?;
answers.extend(apply_decisions(&mut spec, &command.decisions)?);
if fresh || !answers.is_empty() {
let round = spec["rounds"].as_u64().unwrap_or(0) + 1;
let (max_questions, max_rounds) = limits(&spec);
let finalize = round >= max_rounds || command.proceed;
let repo = Repo::open(cwd)?;
let profile = contract::profile(command.roles.as_deref())?;
let agent = adapter::select(command.agent.as_deref(), &repo.root)?;
let request = json!({
"schema_version": 1,
"role": "specify",
"idea": spec["idea"],
"spec": if fresh { Value::Null } else { body(&spec) },
"answers": answers
.iter()
.map(|item| json!({"id": item["id"], "question": item["question"], "answer": item["answer"]}))
.collect::<Vec<_>>(),
"round": round,
"finalize": finalize,
"depth": spec["depth"],
"max_questions": if finalize { 0 } else { max_questions },
"principles": principles_or_note(&repo.root)?,
});
eprintln!(
"agengo: spec round {round} · {} · timeout {}s",
adapter::label(agent.as_deref(), command.auth),
command.timeout
);
let invocation = adapter::invoke_measured(
agent.as_deref(),
command.auth,
&request,
&repo.root,
command.timeout,
&profile,
&crate::config::load(&repo.root)?,
);
if let Some(summary) = invocation
.usage
.as_ref()
.and_then(crate::usage::describe_call)
{
eprintln!("agengo: spec round {round} used {summary}");
}
let reply = invocation.reply?;
revise(&mut spec, &reply, finalize).context("invalid specify reply")?;
spec["rounds"] = json!(round);
spec["approved"] = Value::Null;
validate(&spec)?;
save(&path, &spec)?;
let revised = before.map(|before| changes(&before, &spec));
report(&spec, &path, revised.as_deref(), command.json)?;
return Ok(exit_code(&spec));
} else if changed {
spec["approved"] = Value::Null;
save(&path, &spec)?;
}
report(&spec, &path, None, command.json)?;
Ok(exit_code(&spec))
}
fn exit_code(spec: &Value) -> i32 {
if array_or_empty(&spec["questions"]).is_empty() {
0
} else {
2
}
}
fn lock(path: &Path, spec: &mut Value) -> Result<()> {
let failures = readiness(spec);
if !failures.is_empty() {
bail!(
"{} is not ready to approve:\n- {}",
path.display(),
failures.join("\n- ")
);
}
spec["approved"] = json!({"digest": digest(spec), "at": timestamp()});
save(path, spec)
}
const APPROVAL_CODE_MIN: usize = 6;
pub fn approval_code(spec: &Value) -> String {
digest(spec)["sha256:".len()..][..8].to_owned()
}
pub fn approve_shown(path: &Path, spec: &mut Value, code: &str) -> Result<()> {
let code = code.trim().to_ascii_lowercase();
if code.len() < APPROVAL_CODE_MIN || !code.chars().all(|c| c.is_ascii_hexdigit()) {
bail!(
"approval code {code:?} is not valid; use the code agengo spec printed for the version you reviewed"
);
}
let current = digest(spec);
if !current["sha256:".len()..].starts_with(&code) {
bail!(
"{} changed since approval code {code} was shown (it is now {}); review it again with agengo spec {}",
path.display(),
approval_code(spec),
shell_word(path)
);
}
if approved(spec) {
return Ok(());
}
lock(path, spec)
}
pub fn changes(before: &Value, after: &Value) -> Vec<String> {
let mut lines = Vec::new();
if before["problem"] != after["problem"] {
lines.push(format!("~ problem: {}", string_or_empty(&after["problem"])));
}
for (key, label) in [
("stories", "title"),
("requirements", "text"),
("success_criteria", "text"),
("assumptions", "text"),
] {
let old = array_or_empty(&before[key]);
let new = array_or_empty(&after[key]);
let find =
|items: &[Value], id: &Value| items.iter().find(|item| item["id"] == *id).cloned();
for item in new {
let line = format!(
"{} {}",
string_or_empty(&item["id"]),
string_or_empty(&item[label])
);
match find(old, &item["id"]) {
None => lines.push(format!("+ {line}")),
Some(previous) if previous != *item => lines.push(format!("~ {line}")),
Some(_) => {}
}
}
for item in old.iter().filter(|item| find(new, &item["id"]).is_none()) {
lines.push(format!(
"- {} {}",
string_or_empty(&item["id"]),
string_or_empty(&item[label])
));
}
}
for key in ["actors", "out_of_scope", "constraints", "feasibility"] {
let old = array_or_empty(&before[key]);
let new = array_or_empty(&after[key]);
for item in new.iter().filter(|item| !old.contains(item)) {
lines.push(format!("+ {key}: {}", string_or_empty(item)));
}
for item in old.iter().filter(|item| !new.contains(item)) {
lines.push(format!("- {key}: {}", string_or_empty(item)));
}
}
lines
}
fn empty(idea: &str) -> Value {
json!({
"schema_version": 1, "idea": idea, "problem": "", "actors": [], "stories": [],
"requirements": [], "success_criteria": [], "out_of_scope": [], "constraints": [],
"assumptions": [], "feasibility": [], "questions": [], "clarifications": [],
"depth": DEFAULT_DEPTH, "rounds": 0, "questions_issued": 0, "approved": null,
})
}
fn limits(spec: &Value) -> (usize, u64) {
let depth = spec["depth"].as_str().unwrap_or(DEFAULT_DEPTH);
DEPTHS
.iter()
.find(|(name, ..)| *name == depth)
.map_or((5, 3), |(_, questions, rounds)| (*questions, *rounds))
}
fn body(spec: &Value) -> Value {
Value::Object(
BODY.iter()
.map(|key| ((*key).to_owned(), spec[*key].clone()))
.collect(),
)
}
pub fn load(path: &Path) -> Result<Value> {
let source =
fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
let mut spec: Value = serde_yaml_ng::from_str(&source)
.with_context(|| format!("{} is not valid YAML or JSON", path.display()))?;
if let Some(fields) = spec.as_object_mut() {
fields
.entry("depth")
.or_insert_with(|| json!(DEFAULT_DEPTH));
}
validate(&spec).with_context(|| format!("invalid spec {}", path.display()))?;
Ok(spec)
}
fn save(path: &Path, spec: &Value) -> Result<()> {
let yaml = serde_yaml_ng::to_string(&ordered(spec)?)?;
let directory = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(directory)
.with_context(|| format!("cannot create {}", directory.display()))?;
let mut file = tempfile::NamedTempFile::new_in(directory)?;
file.write_all(yaml.as_bytes())?;
#[cfg(unix)]
file.as_file()
.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o644))?;
file.persist(path)
.with_context(|| format!("cannot write {}", path.display()))?;
Ok(())
}
fn ordered(value: &Value) -> Result<serde_yaml_ng::Value> {
Ok(match value {
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort_by_key(|key| {
(
KEY_ORDER
.iter()
.position(|known| known == key)
.unwrap_or(KEY_ORDER.len()),
(*key).clone(),
)
});
let mut mapping = serde_yaml_ng::Mapping::new();
for key in keys {
mapping.insert(
serde_yaml_ng::Value::String(key.clone()),
ordered(&map[key])?,
);
}
serde_yaml_ng::Value::Mapping(mapping)
}
Value::Array(items) => {
serde_yaml_ng::Value::Sequence(items.iter().map(ordered).collect::<Result<_>>()?)
}
other => serde_yaml_ng::to_value(other)?,
})
}
fn apply_answers(spec: &mut Value, answers: &[String], proceed: bool) -> Result<Vec<Value>> {
let round = spec["rounds"].as_u64().unwrap_or(0).max(1);
let mut open = array_or_empty(&spec["questions"]).to_vec();
let mut records = Vec::new();
for answer in answers {
let (id, value) = answer
.split_once('=')
.with_context(|| format!("expected Q-n=VALUE, got {answer:?}"))?;
let (id, value) = (id.trim(), value.trim());
if value.is_empty() {
bail!("the answer to {id} is empty");
}
let index = open
.iter()
.position(|question| question["id"] == id)
.with_context(|| format!("{id} is not an open question in this spec"))?;
let question = open.remove(index);
records.push(record(&question, Some(value), round));
}
if proceed {
records.extend(
open.drain(..)
.map(|question| record(&question, None, round)),
);
}
spec["questions"] = json!(open);
spec["clarifications"]
.as_array_mut()
.context("clarifications must be a list")?
.extend(records.iter().cloned());
Ok(records)
}
fn apply_decisions(spec: &mut Value, decisions: &[String]) -> Result<Vec<Value>> {
let round = spec["rounds"].as_u64().unwrap_or(0) + 1;
let mut issued = counter(spec, "questions_issued")?;
let mut records = Vec::new();
for decision in decisions {
let decision = json!(decision.trim());
let decision = text(&decision, "decision")?;
issued += 1;
records.push(json!({
"round": round, "id": format!("Q-{issued}"), "question": DECISION,
"answer": decision, "source": "free",
}));
}
spec["questions_issued"] = json!(issued);
spec["clarifications"]
.as_array_mut()
.context("clarifications must be a list")?
.extend(records.iter().cloned());
Ok(records)
}
fn record(question: &Value, value: Option<&str>, round: u64) -> Value {
let label = |key: &str| {
array_or_empty(&question["options"])
.iter()
.find(|option| string_or_empty(&option["key"]).eq_ignore_ascii_case(key))
.map(|option| string_or_empty(&option["label"]).to_owned())
};
let recommended = string_or_empty(&question["recommended"]);
let (answer, source) = match value {
None => (label(recommended), "recommended"),
Some(value) if value.eq_ignore_ascii_case("yes") => (label(recommended), "recommended"),
Some(value) => match label(value) {
Some(label) => (Some(label), "option"),
None => (Some(value.to_owned()), "free"),
},
};
json!({
"round": round, "id": question["id"], "question": question["question"],
"answer": answer.unwrap_or_default(), "source": source,
})
}
fn revise(spec: &mut Value, reply: &Value, finalize: bool) -> Result<()> {
if reply
.get("schema_version")
.is_some_and(|version| version.as_u64() != Some(1))
{
bail!("unsupported schema_version; expected 1");
}
let mut allowed = BODY.to_vec();
allowed.extend(["candidate_questions", "schema_version"]);
contract::fields(reply, "reply", &allowed)?;
for key in BODY {
spec[key] = reply
.get(key)
.with_context(|| format!("missing {key}"))?
.clone();
}
validate_body(spec)?;
let candidates = list(reply, "candidate_questions")?;
if finalize {
if !candidates.is_empty() {
eprintln!(
"agengo: ignored {} because this is the final round",
contract::count(candidates.len(), "question")
);
}
spec["questions"] = json!([]);
return Ok(());
}
let mut accepted = Vec::new();
for candidate in candidates {
match question_problem(candidate, false) {
None => accepted.push(candidate.clone()),
Some(problem) => eprintln!(
"agengo: dropped a question that breaks the question rules ({problem}): {}",
string_or_empty(&candidate["question"])
),
}
}
accepted.sort_by_key(|question| {
(
rank(&IMPACTS, &question["impact"]),
rank(&CATEGORIES, &question["category"]),
)
});
let (max_questions, _) = limits(spec);
if accepted.len() > max_questions {
eprintln!(
"agengo: kept the {max_questions} most important of {} questions",
accepted.len()
);
accepted.truncate(max_questions);
}
let mut issued = counter(spec, "questions_issued")?;
let questions: Vec<Value> = accepted
.into_iter()
.map(|question| {
issued += 1;
let mut numbered = Map::new();
numbered.insert("id".into(), json!(format!("Q-{issued}")));
if let Value::Object(fields) = question {
numbered.extend(fields);
}
Value::Object(numbered)
})
.collect();
spec["questions"] = json!(questions);
spec["questions_issued"] = json!(issued);
Ok(())
}
fn rank(order: &[&str], value: &Value) -> usize {
let value = string_or_empty(value);
order
.iter()
.position(|item| *item == value)
.unwrap_or(order.len())
}
pub fn readiness(spec: &Value) -> Vec<String> {
let id = |item: &Value| string_or_empty(&item["id"]).to_owned();
let mut failures = Vec::new();
let high: Vec<_> = array_or_empty(&spec["questions"])
.iter()
.filter(|question| question["impact"] == "high")
.map(id)
.collect();
if !high.is_empty() {
failures.push(format!(
"R1: answer the high-impact questions {}",
high.join(", ")
));
}
let stories = array_or_empty(&spec["stories"]);
let p1: Vec<_> = stories
.iter()
.filter(|story| story["priority"] == "P1")
.collect();
if p1.is_empty() {
failures.push("R2: no P1 story".into());
}
let bare: Vec<_> = stories
.iter()
.filter(|story| array_or_empty(&story["scenarios"]).is_empty())
.map(id)
.collect();
if !bare.is_empty() {
failures.push(format!(
"R3: stories without a scenario: {}",
bare.join(", ")
));
}
let requirements = array_or_empty(&spec["requirements"]);
let uncovered: Vec<_> = p1
.iter()
.filter(|story| !requirements.iter().any(|item| item["story"] == story["id"]))
.map(|story| id(story))
.collect();
if !uncovered.is_empty() {
failures.push(format!(
"R4: P1 stories without a requirement: {}",
uncovered.join(", ")
));
}
if array_or_empty(&spec["success_criteria"]).is_empty() {
failures.push("R5: no success criterion".into());
}
if array_or_empty(&spec["out_of_scope"]).is_empty() {
failures.push("R6: out_of_scope is empty; name what will not be built".into());
}
if string_or_empty(&spec["problem"]).trim().is_empty()
|| array_or_empty(&spec["actors"]).is_empty()
{
failures.push("R7: problem and actors must be stated".into());
}
failures
}
pub fn digest(spec: &Value) -> String {
let mut unapproved = spec.clone();
if let Some(fields) = unapproved.as_object_mut() {
fields.remove("approved");
}
let mut canonical = String::new();
write_canonical(&unapproved, &mut canonical);
let hash = Sha256::digest(canonical.as_bytes());
format!(
"sha256:{}",
hash.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>()
)
}
fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
out.push('{');
for (index, key) in keys.into_iter().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str(&Value::String(key.clone()).to_string());
out.push(':');
write_canonical(&map[key], out);
}
out.push('}');
}
Value::Array(items) => {
out.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
other => out.push_str(&other.to_string()),
}
}
pub fn select_stories(spec: &Value, selection: Option<&str>) -> Result<Vec<String>> {
let stories = array_or_empty(&spec["stories"]);
let wanted: Vec<&str> = selection
.unwrap_or("P1")
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty())
.collect();
if wanted.is_empty() {
bail!("--stories needs priorities such as P1 or story IDs such as US-1");
}
let matches = |story: &Value, item: &str| story["priority"] == item || story["id"] == item;
if let Some(item) = wanted
.iter()
.find(|item| !stories.iter().any(|story| matches(story, item)))
{
bail!("no story in the spec matches {item}");
}
Ok(stories
.iter()
.filter(|story| wanted.iter().any(|item| matches(story, item)))
.map(|story| string_or_empty(&story["id"]).to_owned())
.collect())
}
fn chosen<'a>(spec: &'a Value, key: &str, field: &str, ids: &[String]) -> Vec<&'a Value> {
array_or_empty(&spec[key])
.iter()
.filter(|item| ids.iter().any(|id| item[field] == id.as_str()))
.collect()
}
pub fn planning_view(spec: &Value, stories: &[String]) -> Value {
json!({
"problem": spec["problem"], "actors": spec["actors"],
"stories": chosen(spec, "stories", "id", stories),
"requirements": chosen(spec, "requirements", "story", stories),
"success_criteria": spec["success_criteria"], "out_of_scope": spec["out_of_scope"],
"constraints": spec["constraints"], "assumptions": spec["assumptions"],
"feasibility": spec["feasibility"],
})
}
pub fn approved(spec: &Value) -> bool {
spec["approved"]["digest"].as_str() == Some(digest(spec).as_str())
}
fn timestamp() -> String {
civil(now_seconds())
}
fn civil(seconds: u64) -> String {
let (days, rest) = ((seconds / 86_400) as i64, seconds % 86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rest / 3_600,
rest % 3_600 / 60,
rest % 60
)
}
fn shell_word(path: &Path) -> String {
let text = path.display().to_string();
if text.chars().any(char::is_whitespace) {
format!("'{text}'")
} else {
text
}
}
fn report(spec: &Value, path: &Path, changes: Option<&[String]>, json: bool) -> Result<()> {
let failures = readiness(spec);
let approved = approved(spec);
let questions = array_or_empty(&spec["questions"]);
let code =
(!approved && questions.is_empty() && failures.is_empty()).then(|| approval_code(spec));
if json {
let mut summary = json!({
"path": path.display().to_string(), "round": spec["rounds"], "depth": spec["depth"],
"questions": questions,
"readiness": {"ready": failures.is_empty(), "failures": failures},
"approved": approved,
});
if let Some(changes) = changes {
summary["changes"] = json!(changes);
}
if let Some(code) = &code {
summary["approval_code"] = json!(code);
}
println!("{}", serde_json::to_string_pretty(&summary)?);
return Ok(());
}
let state = if approved {
"approved"
} else if !questions.is_empty() {
"waiting for answers"
} else if failures.is_empty() {
"ready to approve"
} else {
"not ready"
};
let file = shell_word(path);
let rounds = spec["rounds"].as_u64().unwrap_or(0);
let (_, max_rounds) = limits(spec);
let round = if rounds > max_rounds {
format!("round {rounds}, after the interview")
} else {
format!("round {rounds} of {max_rounds}")
};
println!(
"[SPEC] {file} · {round} ({} depth) · {state}",
string_or_empty(&spec["depth"])
);
let problem = string_or_empty(&spec["problem"]);
if !problem.trim().is_empty() {
println!("Problem: {problem}");
}
match changes {
Some([]) => println!(
"Changed this round: nothing in the problem, stories, requirements, success criteria, scope or assumptions"
),
Some(changes) => {
println!("Changed this round:");
for change in changes {
println!(" {change}");
}
}
None => {}
}
if !questions.is_empty() {
for question in questions {
println!(
"\n{} [{} · {}] {}",
string_or_empty(&question["id"]),
string_or_empty(&question["category"]),
string_or_empty(&question["impact"]),
string_or_empty(&question["question"])
);
println!(" Why: {}", string_or_empty(&question["why"]));
let recommended = string_or_empty(&question["recommended"]);
for option in array_or_empty(&question["options"]) {
let key = string_or_empty(&option["key"]);
println!(
" {key}) {}: {}{}",
string_or_empty(&option["label"]),
string_or_empty(&option["implication"]),
if key.eq_ignore_ascii_case(recommended) {
" ★ recommended"
} else {
""
}
);
}
}
println!(
"\nCommand — agengo spec {file} --answer {}=<option key, yes, or your own words> (repeat per question), or --proceed to accept every recommendation",
string_or_empty(&questions[0]["id"])
);
return Ok(());
}
for story in array_or_empty(&spec["stories"]) {
println!(
"- {} [{}] {}",
string_or_empty(&story["id"]),
string_or_empty(&story["priority"]),
string_or_empty(&story["title"])
);
}
let out_of_scope: Vec<_> = array_or_empty(&spec["out_of_scope"])
.iter()
.map(string_or_empty)
.collect();
if !out_of_scope.is_empty() {
println!("Not built: {}", out_of_scope.join("; "));
}
for impact in ["high", "medium"] {
for assumption in array_or_empty(&spec["assumptions"])
.iter()
.filter(|item| item["impact"] == impact)
{
println!(
"Assumed {} [{impact}]: {} (if wrong: {})",
string_or_empty(&assumption["id"]),
string_or_empty(&assumption["text"]),
string_or_empty(&assumption["if_wrong"])
);
}
}
for note in array_or_empty(&spec["feasibility"]) {
println!("Feasibility: {}", string_or_empty(note));
}
for failure in &failures {
println!("Not ready — {failure}");
}
if let Some(code) = code {
println!("Command — agengo spec {file} --approve");
println!("Command — agengo plan --spec {file} --approve-spec {code} (approve this version and draft the plan)");
}
Ok(())
}