use super::*;
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);
};
if !Path::new(&reference.path).is_absolute() {
crate::contract::scope_path(&reference.path)
.with_context(|| format!("plan spec path {:?}", reference.path))?;
}
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"],
})))
}