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_refuses_a_spec_path_that_climbs_out_of_the_repository() -> Result<()> {
let directory = tempfile::tempdir()?;
let spec = approved_spec(directory.path())?;
let mut plan = traced_plan(&spec, &[&["FR-1", "FR-2"]])?;
plan.spec.as_mut().unwrap().path = "../spec.yaml".into();
let error = coverage(&plan, directory.path()).unwrap_err();
assert!(format!("{error:#}").contains("invalid repository-relative path"));
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(())
}
#[test]
fn decisions_get_fresh_ids_and_the_next_round() -> Result<()> {
let mut spec = empty("idea");
spec["rounds"] = json!(2);
spec["questions_issued"] = json!(4);
let records = apply_decisions(
&mut spec,
&[" Use weekly totals ".into(), "Keep it local".into()],
)?;
assert_eq!(records[0]["id"], "Q-5");
assert_eq!(records[1]["id"], "Q-6");
assert_eq!(records[0]["answer"], "Use weekly totals", "text is trimmed");
assert_eq!(records[0]["round"], 3);
assert_eq!(records[0]["source"], "free");
assert_eq!(spec["questions_issued"], 6);
assert_eq!(array_or_empty(&spec["clarifications"]).len(), 2);
validate(&spec)?;
assert!(apply_decisions(&mut spec, &[" ".into()]).is_err());
assert_eq!(spec["questions_issued"], 6);
Ok(())
}
#[test]
fn proceeding_turns_unanswered_questions_into_recommendations() -> Result<()> {
let mut spec = empty("idea");
spec["rounds"] = json!(2);
spec["questions_issued"] = json!(2);
spec["questions"] = json!([1, 2]
.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-2=B".into()], true)?;
assert_eq!(records.len(), 2);
assert_eq!(records[0]["source"], "option");
assert_eq!(records[1]["id"], "Q-1");
assert_eq!(records[1]["source"], "recommended");
assert_eq!(records[1]["round"], 2);
assert_eq!(spec["questions"], json!([]));
assert!(apply_answers(&mut spec.clone(), &["Q-1=".into()], false).is_err());
Ok(())
}
#[test]
fn readiness_reports_stories_without_scenarios_or_requirements_and_missing_actors() {
let mut spec = empty("idea");
spec["problem"] = json!("Orders get lost");
spec["success_criteria"] = json!([{"id": "SC-1", "text": "Fast"}]);
spec["out_of_scope"] = json!(["Payments"]);
spec["stories"] = json!([
{"id": "US-1", "priority": "P1", "title": "Sell", "scenarios": []},
{"id": "US-2", "priority": "P2", "title": "Report", "scenarios": ["Given, When, Then"]}]);
spec["requirements"] = json!([{"id": "FR-1", "story": "US-2", "text": "Totals"}]);
let failures = readiness(&spec);
assert_eq!(failures.len(), 3, "{failures:?}");
assert!(failures[0].starts_with("R3") && failures[0].contains("US-1"));
assert!(failures[1].starts_with("R4") && failures[1].contains("US-1"));
assert!(failures[2].starts_with("R7"));
}
#[test]
fn spec_ids_must_look_like_their_prefix() {
let id = |text: &str, prefix: &str| numbered(&json!(text), prefix, "id").map(|(_, n)| n);
assert_eq!(id("FR-12", "FR").unwrap(), 12);
assert_eq!(id("FR-9999", "FR").unwrap(), 9999);
for bad in ["FR-", "FR-12345", "FR12", "FR-1a", "SC-1", " FR-1"] {
assert!(id(bad, "FR").is_err(), "{bad:?}");
}
let mut seen = BTreeSet::new();
assert!(unique(&mut seen, &json!("US-1"), "US", "story id").is_ok());
assert_eq!(
unique(&mut seen, &json!("US-1"), "US", "story id")
.unwrap_err()
.to_string(),
"duplicate story id US-1"
);
}
#[test]
fn a_spec_survives_saving_and_loading_with_its_digest() -> Result<()> {
let directory = tempfile::tempdir()?;
let spec = approved_spec(directory.path())?;
let loaded = load(&directory.path().join("spec.yaml"))?;
assert_eq!(digest(&loaded), digest(&spec));
assert!(approved(&loaded));
let mut edited = loaded;
edited["problem"] = json!("Something else");
assert!(!approved(&edited));
Ok(())
}
#[test]
fn changes_lists_what_a_revision_added_removed_and_changed() -> Result<()> {
let directory = tempfile::tempdir()?;
let before = approved_spec(directory.path())?;
let mut after = before.clone();
after["requirements"][1]["text"] = json!("Lower the stock");
after["requirements"]
.as_array_mut()
.context("requirements")?
.remove(2);
after["requirements"]
.as_array_mut()
.context("requirements")?
.push(json!({"id": "FR-4", "story": "US-1", "text": "Email receipts"}));
after["out_of_scope"] = json!(["Printed receipts"]);
let lines = changes(&before, &after);
assert!(
lines.contains(&"~ FR-2 Lower the stock".to_owned()),
"{lines:?}"
);
assert!(lines.contains(&"- FR-3 Totals".to_owned()), "{lines:?}");
assert!(
lines.contains(&"+ FR-4 Email receipts".to_owned()),
"{lines:?}"
);
assert!(
lines.contains(&"+ out_of_scope: Printed receipts".to_owned()),
"{lines:?}"
);
let mut unapproved = before.clone();
unapproved["approved"] = Value::Null;
assert!(changes(&before, &unapproved).is_empty());
Ok(())
}
#[test]
fn approve_shown_locks_only_the_version_whose_code_was_shown() -> Result<()> {
let directory = tempfile::tempdir()?;
let path = directory.path().join("spec.yaml");
let mut spec = approved_spec(directory.path())?;
spec["approved"] = Value::Null;
let code = approval_code(&spec);
assert_eq!(code.len(), 8);
let mut edited = spec.clone();
edited["problem"] = json!("Something else");
let error = approve_shown(&path, &mut edited, &code).unwrap_err();
assert!(
error.to_string().contains("changed since approval code"),
"{error}"
);
assert!(!approved(&edited));
for bad in ["abc", "not-hex!"] {
assert!(approve_shown(&path, &mut spec, bad).is_err(), "{bad}");
}
approve_shown(&path, &mut spec, &format!(" {} ", code.to_uppercase()))?;
assert!(approved(&spec));
assert!(approved(&load(&path)?));
approve_shown(&path, &mut spec, &code[..6])?;
Ok(())
}
#[test]
fn a_kept_draft_is_only_a_cache() -> Result<()> {
let directory = tempfile::tempdir()?;
let repo = Repo {
root: directory.path().into(),
data: directory.path().join("data"),
worktrees: directory.path().join("worktrees"),
};
let stories = vec!["US-1".to_owned()];
let drafts = Drafts::new(&repo, ".agengo/spec.yaml", &stories);
let draft = json!({"tasks": [{"id": "a"}], "questions": ["Print receipts?"]});
let mut spec = json!({"rounds": 1, "clarifications": []});
drafts.remember(&draft, &json!(1))?;
assert_eq!(drafts.previous(&spec)?, None);
spec["clarifications"] = json!([{"round": 2, "question": DECISION, "answer": "No"}]);
let previous = drafts.previous(&spec)?.context("draft kept")?;
assert_eq!(previous["decisions"], json!([{"answer": "No"}]));
assert_eq!(previous["tasks"], draft["tasks"]);
let other = Drafts::new(&repo, ".agengo/spec.yaml", &["US-2".to_owned()]);
assert_eq!(other.previous(&spec)?, None);
let mut kept: Value = serde_json::from_str(&fs::read_to_string(&drafts.file)?)?;
kept["saved_at"] = json!(now_seconds() - DRAFT_MAX_AGE - 1);
fs::write(&drafts.file, serde_json::to_vec(&kept)?)?;
assert_eq!(drafts.previous(&spec)?, None);
fs::write(&drafts.file, "{\"spec\": \".agengo/sp")?;
assert_eq!(drafts.previous(&spec)?, None);
drafts.forget()?;
assert!(!drafts.file.exists());
drafts.forget()?;
Ok(())
}