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";
const PRINCIPLES_LIMIT: usize = 32 * 1024;
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.yaml"));
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 {
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)?;
report(&spec, &path, command.json)?;
return Ok(0);
}
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::executable(command.agent.as_deref())?;
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(&repo.root)?,
});
let invocation = adapter::invoke_measured(
agent.as_deref(),
command.auth,
&request,
&repo.root,
command.timeout,
&profile,
);
if let Some(summary) = invocation.usage.as_ref().and_then(crate::usage::describe) {
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)?;
} else if changed {
spec["approved"] = Value::Null;
save(&path, &spec)?;
}
report(&spec, &path, command.json)?;
Ok(if array_or_empty(&spec["questions"]).is_empty() {
0
} else {
2
})
}
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("."));
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 list<'a>(value: &'a Value, key: &str) -> Result<&'a Vec<Value>> {
value[key]
.as_array()
.with_context(|| format!("{key} must be a list"))
}
fn counter(spec: &Value, key: &str) -> Result<u64> {
spec[key]
.as_u64()
.with_context(|| format!("{key} must be a non-negative integer"))
}
fn numbered(value: &Value, prefix: &str, label: &str) -> Result<(String, u64)> {
let id = text(value, label)?;
let number = id
.strip_prefix(prefix)
.and_then(|rest| rest.strip_prefix('-'))
.filter(|digits| {
(1..=4).contains(&digits.len()) && digits.bytes().all(|c| c.is_ascii_digit())
})
.with_context(|| format!("{label} {id:?} must look like {prefix}-1"))?;
Ok((id.to_owned(), number.parse()?))
}
fn unique(seen: &mut BTreeSet<String>, value: &Value, prefix: &str, label: &str) -> Result<String> {
let (id, _) = numbered(value, prefix, label)?;
if !seen.insert(id.clone()) {
bail!("duplicate {label} {id}");
}
Ok(id)
}
pub fn validate(spec: &Value) -> Result<()> {
let allowed: Vec<&str> = BODY.iter().chain(SESSION.iter()).copied().collect();
contract::fields(spec, "spec", &allowed)?;
if let Some(key) = allowed.iter().find(|key| spec.get(**key).is_none()) {
bail!("spec is missing {key}");
}
if spec["schema_version"].as_u64() != Some(1) {
bail!("unsupported spec schema_version; expected 1");
}
text(&spec["idea"], "idea")?;
validate_body(spec)?;
counter(spec, "rounds")?;
let issued = counter(spec, "questions_issued")?;
let questions = list(spec, "questions")?;
let depth = string_or_empty(&spec["depth"]);
if !DEPTHS.iter().any(|(name, ..)| *name == depth) {
bail!("depth must be quick, standard or deep");
}
let (max_questions, _) = limits(spec);
if questions.len() > max_questions {
bail!("a {depth} spec holds at most {max_questions} open questions");
}
let mut ids = BTreeSet::new();
for question in questions {
let (id, number) = numbered(&question["id"], "Q", "question id")?;
if let Some(problem) = question_problem(question, true) {
bail!("question {id}: {problem}");
}
if !ids.insert(id.clone()) || number > issued {
bail!("question id {id} is repeated or was never issued");
}
}
for item in list(spec, "clarifications")? {
contract::fields(
item,
"clarification",
&["round", "id", "question", "answer", "source"],
)?;
if item["round"].as_u64().unwrap_or(0) < 1 {
bail!("clarification round must be a positive integer");
}
numbered(&item["id"], "Q", "clarification id")?;
text(&item["question"], "clarification question")?;
text(&item["answer"], "clarification answer")?;
if !SOURCES.contains(&string_or_empty(&item["source"])) {
bail!("clarification source must be one of {}", SOURCES.join(", "));
}
}
let approved = &spec["approved"];
if !approved.is_null() {
contract::fields(approved, "approved", &["digest", "at"])?;
if !text(&approved["digest"], "approved digest")?.starts_with("sha256:") {
bail!("approved digest must start with sha256:");
}
text(&approved["at"], "approved at")?;
}
Ok(())
}
fn validate_body(spec: &Value) -> Result<()> {
if !spec["problem"].is_string() {
bail!("problem must be a string");
}
for key in ["actors", "out_of_scope", "constraints", "feasibility"] {
for item in list(spec, key)? {
text(item, key)?;
}
}
let mut stories = BTreeSet::new();
for story in list(spec, "stories")? {
contract::fields(story, "story", &["id", "priority", "title", "scenarios"])?;
let id = unique(&mut stories, &story["id"], "US", "story id")?;
if !PRIORITIES.contains(&string_or_empty(&story["priority"])) {
bail!("story {id}: priority must be P1, P2 or P3");
}
text(&story["title"], "story title")?;
for scenario in list(story, "scenarios")? {
text(scenario, "story scenario")?;
}
}
let mut requirements = BTreeSet::new();
for item in list(spec, "requirements")? {
contract::fields(item, "requirement", &["id", "story", "text"])?;
let id = unique(&mut requirements, &item["id"], "FR", "requirement id")?;
if !stories.contains(string_or_empty(&item["story"])) {
bail!("requirement {id} refers to unknown story {}", item["story"]);
}
text(&item["text"], "requirement text")?;
}
let mut criteria = BTreeSet::new();
for item in list(spec, "success_criteria")? {
contract::fields(item, "success criterion", &["id", "text"])?;
unique(&mut criteria, &item["id"], "SC", "success criterion id")?;
text(&item["text"], "success criterion text")?;
}
let mut assumptions = BTreeSet::new();
for item in list(spec, "assumptions")? {
contract::fields(item, "assumption", &["id", "text", "impact", "if_wrong"])?;
let id = unique(&mut assumptions, &item["id"], "A", "assumption id")?;
if !IMPACTS.contains(&string_or_empty(&item["impact"])) {
bail!("assumption {id}: impact must be high, medium or low");
}
text(&item["text"], "assumption text")?;
text(&item["if_wrong"], "assumption if_wrong")?;
}
Ok(())
}
fn question_problem(question: &Value, stored: bool) -> Option<String> {
let mut allowed = vec![
"category",
"impact",
"question",
"why",
"options",
"recommended",
];
if stored {
allowed.push("id");
}
if let Err(error) = contract::fields(question, "question", &allowed) {
return Some(error.to_string());
}
let category = string_or_empty(&question["category"]);
if !CATEGORIES.contains(&category) {
return Some(format!(
"category {category:?} is not one of {}",
CATEGORIES.join(", ")
));
}
if !IMPACTS.contains(&string_or_empty(&question["impact"])) {
return Some("impact must be high, medium or low".into());
}
for key in ["question", "why"] {
if text(&question[key], key).is_err() {
return Some(format!("{key} is empty"));
}
}
let options = array_or_empty(&question["options"]);
if !(2..=MAX_OPTIONS).contains(&options.len()) {
return Some(format!(
"needs 2 to {MAX_OPTIONS} options, has {}",
options.len()
));
}
let mut keys = BTreeSet::new();
for option in options {
if let Err(error) = contract::fields(option, "option", &["key", "label", "implication"]) {
return Some(error.to_string());
}
for key in ["key", "label", "implication"] {
if text(&option[key], key).is_err() {
return Some(format!("an option has an empty {key}"));
}
}
let key = string_or_empty(&option["key"]).to_ascii_uppercase();
if key == "YES" || !keys.insert(key) {
return Some("option keys must be distinct and not \"yes\"".into());
}
}
if !keys.contains(&string_or_empty(&question["recommended"]).to_ascii_uppercase()) {
return Some("recommended is not one of the option keys".into());
}
None
}
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 stored_path(path: &Path, root: &Path) -> Result<String> {
let absolute =
fs::canonicalize(path).with_context(|| format!("cannot read {}", path.display()))?;
let root = fs::canonicalize(root)?;
Ok(match absolute.strip_prefix(&root) {
Ok(relative) => relative
.components()
.map(|part| part.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/"),
Err(_) => absolute.display().to_string(),
})
}
pub fn coverage(plan: &Plan, root: &Path) -> Result<Option<(Value, Vec<String>)>> {
let Some(reference) = &plan.spec else {
return Ok(None);
};
let path = root.join(&reference.path);
let spec = load(&path)?;
if !approved(&spec) {
bail!(
"C0: {} is not approved or changed after approval; approve it with agengo spec {} --approve and draft the plan again",
path.display(),
path.display()
);
}
if spec["approved"]["digest"] != reference.digest.as_str() {
bail!(
"C0: the plan was drafted from another version of {}; draft it again with agengo plan --spec",
path.display()
);
}
let stories = chosen(&spec, "stories", "id", &reference.stories);
if let Some(missing) = reference
.stories
.iter()
.find(|id| !stories.iter().any(|story| story["id"] == id.as_str()))
{
bail!("C0: story {missing} is not in {}", path.display());
}
let known: BTreeSet<&str> = array_or_empty(&spec["requirements"])
.iter()
.chain(array_or_empty(&spec["success_criteria"]))
.map(|item| string_or_empty(&item["id"]))
.collect();
let selected: Vec<&str> = chosen(&spec, "requirements", "story", &reference.stories)
.into_iter()
.map(|item| string_or_empty(&item["id"]))
.collect();
let mut covered = BTreeSet::new();
let mut outside = BTreeSet::new();
let mut unreferenced = Vec::new();
for task in &plan.tasks {
for criterion in task.criteria() {
if criterion.refs.is_empty() {
unreferenced.push(format!("{}/{}", task.id, criterion.id));
}
for id in criterion.refs {
if !known.contains(id.as_str()) {
bail!(
"C1: {}/{} refers to {id}, which is not in {}",
task.id,
criterion.id,
path.display()
);
}
if id.starts_with("FR-") && !selected.contains(&id.as_str()) {
outside.insert(id.clone());
}
covered.insert(id);
}
}
}
let missing: Vec<&str> = selected
.iter()
.copied()
.filter(|id| !covered.contains(*id))
.collect();
if !missing.is_empty() {
bail!(
"C2: no acceptance criterion checks {}; give each a criterion whose refs name it",
missing.join(", ")
);
}
let mut warnings = Vec::new();
if !outside.is_empty() {
warnings.push(format!(
"C3: acceptance criteria refer to requirements outside stories {}: {}",
reference.stories.join(", "),
outside.into_iter().collect::<Vec<_>>().join(", ")
));
}
if !unreferenced.is_empty() {
warnings.push(format!(
"C4: acceptance criteria without spec refs: {}",
unreferenced.join(", ")
));
}
Ok(Some((spec, warnings)))
}
pub fn keep_with_run(store: &Store, run: &str, plan: &Plan, spec: Option<&Value>) -> Result<()> {
match (&plan.spec, spec) {
(Some(reference), Some(body)) => store.0.execute(
"INSERT OR REPLACE INTO run_specs (run_id,path,digest,stories,body) VALUES (?,?,?,?,?)",
rusqlite::params![
run,
reference.path,
reference.digest,
json!(reference.stories).to_string(),
body.to_string()
],
)?,
_ => store
.0
.execute("DELETE FROM run_specs WHERE run_id=?", [run])?,
};
Ok(())
}
pub fn assignment_view(store: &Store, run: &str, task: &Task) -> Result<Option<Value>> {
let Some(row) = store.one(
"SELECT stories, body FROM run_specs WHERE run_id=?",
&[&run],
)?
else {
return Ok(None);
};
let stories: Vec<String> = serde_json::from_str(string_or_empty(&row["stories"]))?;
let spec: Value = serde_json::from_str(string_or_empty(&row["body"]))?;
let refs: BTreeSet<String> = task
.criteria()
.into_iter()
.flat_map(|criterion| criterion.refs)
.collect();
let requirements: Vec<&Value> = if refs.is_empty() {
chosen(&spec, "requirements", "story", &stories)
} else {
array_or_empty(&spec["requirements"])
.iter()
.filter(|item| refs.contains(string_or_empty(&item["id"])))
.collect()
};
Ok(Some(json!({
"requirements": requirements, "success_criteria": spec["success_criteria"],
"out_of_scope": spec["out_of_scope"],
})))
}
pub fn approved(spec: &Value) -> bool {
spec["approved"]["digest"].as_str() == Some(digest(spec).as_str())
}
fn timestamp() -> String {
civil(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs()),
)
}
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, json: bool) -> Result<()> {
let failures = readiness(spec);
let approved = approved(spec);
let questions = array_or_empty(&spec["questions"]);
if json {
let summary = json!({
"path": path.display().to_string(), "round": spec["rounds"], "depth": spec["depth"],
"questions": questions,
"readiness": {"ready": failures.is_empty(), "failures": failures},
"approved": approved,
});
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}");
}
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 !approved && failures.is_empty() {
println!("Command — agengo spec {file} --approve");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn question(category: &str, impact: &str) -> Value {
json!({"category": category, "impact": impact, "question": "Who?", "why": "Scope",
"options": [{"key": "A", "label": "Owner", "implication": "Smaller"},
{"key": "B", "label": "Staff", "implication": "Logins"}],
"recommended": "A"})
}
fn ready_body() -> Value {
json!({"problem": "Orders get lost", "actors": ["owner"],
"stories": [{"id": "US-1", "priority": "P1", "title": "Record a sale",
"scenarios": ["Given stock, When I sell, Then stock drops"]}],
"requirements": [{"id": "FR-1", "story": "US-1", "text": "Record a sale"}],
"success_criteria": [{"id": "SC-1", "text": "A sale takes under 30 seconds"}],
"out_of_scope": ["Online payment"], "constraints": [], "assumptions": [],
"feasibility": [], "candidate_questions": []})
}
#[test]
fn civil_time_handles_epoch_and_leap_days() {
assert_eq!(civil(0), "1970-01-01T00:00:00Z");
assert_eq!(civil(951_782_400 + 3_661), "2000-02-29T01:01:01Z");
}
#[test]
fn digest_ignores_key_order_and_approval_but_not_content() {
let left = json!({"a": 1, "b": {"c": [1, 2]}, "approved": null});
let right = json!({"b": {"c": [1, 2]}, "approved": {"digest": "x"}, "a": 1});
assert_eq!(digest(&left), digest(&right));
assert_ne!(digest(&left), digest(&json!({"a": 2, "b": {"c": [1, 2]}})));
assert!(digest(&left).starts_with("sha256:") && digest(&left).len() == 71);
}
#[test]
fn revise_keeps_the_five_most_important_valid_questions() -> Result<()> {
let mut spec = empty("idea");
spec["questions_issued"] = json!(2);
let mut reply = ready_body();
let mut tech = question("scope", "high");
tech["category"] = json!("tech");
reply["candidate_questions"] = json!([
question("terminology", "low"),
question("data", "medium"),
tech,
question("quality", "high"),
question("flow", "medium"),
question("scope", "high"),
question("actors", "high"),
]);
revise(&mut spec, &reply, false)?;
let kept: Vec<_> = array_or_empty(&spec["questions"])
.iter()
.map(|q| {
format!(
"{}:{}",
string_or_empty(&q["id"]),
string_or_empty(&q["category"])
)
})
.collect();
assert_eq!(
kept,
[
"Q-3:scope",
"Q-4:actors",
"Q-5:quality",
"Q-6:flow",
"Q-7:data"
]
);
assert_eq!(spec["questions_issued"], 7);
validate(&spec)?;
revise(&mut spec, &reply, true)?;
assert_eq!(spec["questions"], json!([]));
for (depth, kept) in [("quick", 3), ("deep", 6)] {
let mut spec = empty("idea");
spec["depth"] = json!(depth);
revise(&mut spec, &reply, false)?;
assert_eq!(array_or_empty(&spec["questions"]).len(), kept, "{depth}");
validate(&spec)?;
}
Ok(())
}
#[test]
fn question_rules_reject_unusable_questions() {
assert_eq!(question_problem(&question("scope", "high"), false), None);
let mut single = question("scope", "high");
single["options"].as_array_mut().unwrap().pop();
assert!(question_problem(&single, false).unwrap().contains("2 to 4"));
let mut stray = question("scope", "high");
stray["recommended"] = json!("C");
assert!(question_problem(&stray, false).is_some());
let mut yes = question("scope", "high");
yes["options"][1]["key"] = json!("yes");
assert!(question_problem(&yes, false).is_some());
}
#[test]
fn answers_record_their_source() -> Result<()> {
let mut spec = empty("idea");
spec["rounds"] = json!(1);
spec["questions_issued"] = json!(3);
spec["questions"] = json!([1, 2, 3]
.iter()
.map(|n| {
let mut q = question("scope", "high");
q["id"] = json!(format!("Q-{n}"));
q
})
.collect::<Vec<_>>());
let records = apply_answers(&mut spec, &["Q-1=b".into(), "Q-2 = yes".into()], false)?;
assert_eq!(records[0]["answer"], "Staff");
assert_eq!(records[0]["source"], "option");
assert_eq!(records[1]["answer"], "Owner");
assert_eq!(records[1]["source"], "recommended");
assert!(apply_answers(&mut spec.clone(), &["Q-1=A".into()], false).is_err());
assert!(apply_answers(&mut spec.clone(), &["Q-3".into()], false).is_err());
let records = apply_answers(&mut spec, &["Q-3=Only weekends".into()], false)?;
assert_eq!(records[0]["source"], "free");
assert_eq!(spec["questions"], json!([]));
assert_eq!(array_or_empty(&spec["clarifications"]).len(), 3);
Ok(())
}
#[test]
fn readiness_names_each_missing_part() -> Result<()> {
let mut spec = empty("idea");
assert_eq!(readiness(&spec).len(), 4);
revise(&mut spec, &ready_body(), true)?;
assert_eq!(readiness(&spec), Vec::<String>::new());
spec["out_of_scope"] = json!([]);
spec["questions"] = json!([{"id": "Q-1", "impact": "high"}]);
let failures = readiness(&spec);
assert!(failures[0].starts_with("R1") && failures[1].starts_with("R6"));
Ok(())
}
fn approved_spec(directory: &Path) -> Result<Value> {
let mut spec = empty("idea");
let mut body = ready_body();
body["stories"] = json!([
{"id": "US-1", "priority": "P1", "title": "Sell", "scenarios": ["Given, When, Then"]},
{"id": "US-2", "priority": "P2", "title": "Report", "scenarios": ["Given, When, Then"]}]);
body["requirements"] = json!([
{"id": "FR-1", "story": "US-1", "text": "Record"},
{"id": "FR-2", "story": "US-1", "text": "Stock"},
{"id": "FR-3", "story": "US-2", "text": "Totals"}]);
revise(&mut spec, &body, true)?;
spec["approved"] = json!({"digest": digest(&spec), "at": "now"});
save(&directory.join("spec.yaml"), &spec)?;
Ok(spec)
}
fn traced_plan(spec: &Value, refs: &[&[&str]]) -> Result<Plan> {
let acceptance: Vec<Value> = refs
.iter()
.enumerate()
.map(|(index, refs)| json!({"id": format!("AC-{}", index + 1), "text": "Check", "refs": refs}))
.collect();
Plan::from_value(contract::validate_plan(json!({
"goal": "g", "final_verify": [["true"]],
"spec": {"path": "spec.yaml", "digest": spec["approved"]["digest"], "stories": ["US-1"]},
"tasks": [{"id": "a", "goal": "A", "owns": ["a"], "acceptance": acceptance, "verify": [["true"]]}],
}))?)
}
#[test]
fn principles_are_read_only_once_filled_in() -> Result<()> {
let root = tempfile::tempdir()?;
assert_eq!(principles(root.path())?, None);
let path = root.path().join(PRINCIPLES_PATH);
fs::create_dir_all(path.parent().unwrap())?;
fs::write(&path, include_str!("../specs/principles-template.md"))?;
assert_eq!(principles(root.path())?, None, "the template is empty");
fs::write(
&path,
"# Project principles\n<!-- guidance\nover lines -->\n## Stack\n<!-- hint -->\nRust 1.90\n",
)?;
assert_eq!(
principles(root.path())?.as_deref(),
Some("# Project principles\n\n## Stack\n\nRust 1.90")
);
fs::write(&path, format!("## Never\n{}\n", "x".repeat(40 * 1024)))?;
assert!(principles(root.path()).is_err());
Ok(())
}
#[test]
fn stories_are_chosen_by_priority_or_id() -> Result<()> {
let directory = tempfile::tempdir()?;
let spec = approved_spec(directory.path())?;
assert_eq!(select_stories(&spec, None)?, ["US-1"]);
assert_eq!(select_stories(&spec, Some("US-2, P1"))?, ["US-1", "US-2"]);
assert!(select_stories(&spec, Some("P3")).is_err());
let view = planning_view(&spec, &["US-2".into()]);
assert_eq!(view["requirements"].as_array().map(Vec::len), Some(1));
Ok(())
}
#[test]
fn coverage_rules_c1_to_c4() -> Result<()> {
let directory = tempfile::tempdir()?;
let spec = approved_spec(directory.path())?;
let root = directory.path();
let (_, warnings) = coverage(&traced_plan(&spec, &[&["FR-1", "SC-1"], &["FR-2"]])?, root)?
.expect("the plan names a spec");
assert!(warnings.is_empty(), "{warnings:?}");
let missing = coverage(&traced_plan(&spec, &[&["FR-1"]])?, root).unwrap_err();
assert!(missing
.to_string()
.starts_with("C2: no acceptance criterion checks FR-2"));
let unknown =
coverage(&traced_plan(&spec, &[&["FR-1", "FR-2", "FR-9"]])?, root).unwrap_err();
assert!(unknown.to_string().starts_with("C1: a/AC-1 refers to FR-9"));
let (_, warnings) = coverage(
&traced_plan(&spec, &[&["FR-1", "FR-2", "FR-3"], &[]])?,
root,
)?
.unwrap();
assert!(warnings[0].starts_with("C3:") && warnings[0].ends_with("FR-3"));
assert_eq!(
warnings[1],
"C4: acceptance criteria without spec refs: a/AC-2"
);
let mut stale = traced_plan(&spec, &[&["FR-1", "FR-2"]])?;
stale.spec.as_mut().unwrap().digest = format!("sha256:{}", "0".repeat(64));
assert!(coverage(&stale, root)
.unwrap_err()
.to_string()
.starts_with("C0:"));
Ok(())
}
}