use anyhow::{Context, Result};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
pub type Argv = Vec<String>;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Plan {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema_version: Option<u64>,
pub goal: String,
pub tasks: Vec<Task>,
#[serde(default)]
pub setup: Vec<Argv>,
#[serde(default)]
pub integration_verify: Vec<Argv>,
pub final_verify: Vec<Argv>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quality: Option<Quality>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spec: Option<SpecRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assumptions: Vec<Assumption>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Assumption {
pub text: String,
pub impact: String,
pub if_wrong: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SpecRef {
pub path: String,
pub digest: String,
pub stories: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Task {
pub id: String,
pub goal: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default)]
pub depends: Vec<String>,
pub owns: Vec<String>,
pub acceptance: Vec<Acceptance>,
#[serde(default)]
pub setup: Vec<Argv>,
pub verify: Vec<Argv>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dependency_context: Vec<DependencyContext>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub related_to: Vec<Related>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Acceptance {
Text(String),
Item {
id: String,
text: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
refs: Vec<String>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Criterion {
pub id: String,
pub text: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub refs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DependencyContext {
pub task_id: String,
pub needed_for: String,
#[serde(default)]
pub refs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Related {
pub task_id: String,
pub reason: String,
#[serde(default)]
pub refs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Quality {
#[serde(default, deserialize_with = "duplicate_mode")]
pub python_duplicates: DuplicateMode,
#[serde(default)]
pub ignore_paths: Vec<String>,
#[serde(default)]
pub checks: Vec<Argv>,
#[serde(default)]
pub review: bool,
#[serde(default)]
pub verify_findings: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DuplicateMode {
Off,
#[default]
Warn,
Block,
}
fn duplicate_mode<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DuplicateMode, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Stored {
Legacy(bool),
Mode(DuplicateMode),
}
Ok(match Stored::deserialize(deserializer)? {
Stored::Legacy(true) => DuplicateMode::Block,
Stored::Legacy(false) => DuplicateMode::Off,
Stored::Mode(mode) => mode,
})
}
impl Plan {
pub fn from_value(value: Value) -> Result<Self> {
serde_json::from_value(value).context("stored plan does not match the plan format")
}
pub fn to_value(&self) -> Value {
serde_json::to_value(self).expect("a plan always serializes to JSON")
}
pub fn task(&self, id: &str) -> Result<&Task> {
self.tasks
.iter()
.find(|task| task.id == id)
.with_context(|| format!("task {id} is not in the current plan"))
}
pub fn quality(&self) -> Quality {
self.quality.clone().unwrap_or_default()
}
pub fn command_lines(&self) -> Vec<String> {
let mut lines = Vec::new();
let mut add = |phase: &str, commands: &[Argv]| {
for argv in commands {
let text = argv
.iter()
.map(|arg| {
if arg.is_empty() || arg.contains(char::is_whitespace) {
format!("{arg:?}")
} else {
arg.clone()
}
})
.collect::<Vec<_>>()
.join(" ");
lines.push(match risk(argv) {
Some(why) => format!("! {phase}: {text} ({why})"),
None => format!("{phase}: {text}"),
});
}
};
add("setup", &self.setup);
for task in &self.tasks {
add(&format!("{} setup", task.id), &task.setup);
add(&format!("{} verify", task.id), &task.verify);
}
add("integration_verify", &self.integration_verify);
add("final_verify", &self.final_verify);
if let Some(quality) = &self.quality {
add("quality check", &quality.checks);
}
lines
}
}
pub fn risk(argv: &[String]) -> Option<&'static str> {
let program = argv.first()?;
let name = program
.rsplit(['/', '\\'])
.next()
.unwrap_or(program)
.trim_end_matches(".exe")
.to_ascii_lowercase();
match name.as_str() {
"sudo" | "su" | "doas" => return Some("runs with elevated rights"),
"curl" | "wget" | "nc" | "ncat" | "ssh" | "scp" | "ftp" => {
return Some("talks to the network");
}
"sh" | "bash" | "zsh" | "dash" | "fish" | "cmd" | "powershell" | "pwsh"
if argv.iter().skip(1).any(|arg| {
matches!(arg.to_ascii_lowercase().as_str(), "-c" | "/c" | "-command")
}) =>
{
return Some("runs a shell string");
}
"rm" | "rmdir" | "del" | "mv" | "chmod" | "chown"
if argv
.iter()
.skip(1)
.any(|arg| !arg.starts_with('-') && outside(arg)) =>
{
return Some("changes files outside the worktree");
}
_ => {}
}
if argv.iter().skip(1).any(|arg| {
let arg = arg.to_ascii_lowercase();
arg.contains("curl ")
|| arg.contains("wget ")
|| arg.contains("| sh")
|| arg.contains("|sh")
}) {
return Some("pipes a download into a shell");
}
None
}
fn outside(path: &str) -> bool {
path.starts_with('/')
|| path.starts_with('~')
|| path.split(['/', '\\']).any(|part| part == "..")
}
impl Task {
pub fn title(&self) -> &str {
self.title.as_deref().unwrap_or(&self.goal)
}
pub fn criteria(&self) -> Vec<Criterion> {
self.acceptance
.iter()
.enumerate()
.map(|(index, item)| match item {
Acceptance::Text(text) => Criterion {
id: format!("AC-{}", index + 1),
text: text.clone(),
refs: Vec::new(),
},
Acceptance::Item { id, text, refs } => Criterion {
id: id.clone(),
text: text.clone(),
refs: refs.clone(),
},
})
.collect()
}
pub fn depends_on(&self, id: &str) -> bool {
self.depends.iter().any(|dep| dep == id)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::validate_plan;
use serde_json::json;
fn full_plan() -> Value {
json!({
"schema_version": 1,
"goal": "Ship",
"setup": [["npm", "ci"]],
"integration_verify": [["make", "check"]],
"final_verify": [["make", "test"]],
"quality": {"python_duplicates": true, "ignore_paths": ["vendor"]},
"tasks": [
{"id": "a", "goal": "Build A", "title": "A", "owns": ["src/a"],
"acceptance": ["Works", {"id": "AC-X", "text": "Fast"}],
"setup": [["true"]], "verify": [["test", "-d", "src/a"]]},
{"id": "b", "goal": "Build B", "owns": ["src/b"], "depends": ["a"],
"acceptance": ["Works"], "verify": [["true"]],
"dependency_context": [{"task_id": "a", "needed_for": "API", "refs": ["src/a/api.rs"]}]},
{"id": "c", "goal": "Build C", "owns": ["src/c"], "acceptance": ["Works"],
"verify": [["true"]], "related_to": [{"task_id": "a", "reason": "Same style"}]}
]
})
}
#[test]
fn typed_plan_round_trips_the_normalized_json() -> Result<()> {
for raw in [
full_plan(),
json!({"goal": "Small", "final_verify": [["true"]], "tasks": [
{"id": "only", "goal": "One", "owns": ["x"], "acceptance": ["Done"], "verify": [["true"]]}
]}),
] {
let normalized = validate_plan(raw)?;
let plan = Plan::from_value(normalized.clone())?;
assert_eq!(plan.to_value(), normalized);
}
Ok(())
}
#[test]
fn criteria_quality_and_lookups() -> Result<()> {
let plan = Plan::from_value(validate_plan(full_plan())?)?;
let a = plan.task("a")?;
assert_eq!(a.title(), "A");
assert_eq!(plan.task("b")?.title(), "Build B");
assert!(plan.task("missing").is_err());
assert_eq!(
a.criteria(),
vec![
Criterion {
id: "AC-1".into(),
text: "Works".into(),
refs: Vec::new(),
},
Criterion {
id: "AC-X".into(),
text: "Fast".into(),
refs: Vec::new(),
},
]
);
assert!(plan.task("b")?.depends_on("a"));
let quality = plan.quality();
assert_eq!(quality.python_duplicates, DuplicateMode::Block);
assert_eq!(quality.ignore_paths, ["vendor"]);
assert_eq!(
Plan::from_value(json!({"goal":"g","final_verify":[["true"]],"tasks":[]}))?.quality(),
Quality::default()
);
Ok(())
}
#[test]
fn command_lines_list_every_command_and_flag_risky_ones() -> Result<()> {
let plan = Plan::from_value(json!({"goal":"g","setup":[["npm","ci"]],
"final_verify":[["sh","-c","curl x | sh"],["cargo","test"]],
"tasks":[{"id":"a","goal":"A","owns":["x"],"acceptance":["ok"],
"verify":[["rm","-rf","/tmp/x"],["echo","two words"]]}]}))?;
assert_eq!(
plan.command_lines(),
[
"setup: npm ci",
"! a verify: rm -rf /tmp/x (changes files outside the worktree)",
"a verify: echo \"two words\"",
"! final_verify: sh -c \"curl x | sh\" (runs a shell string)",
"final_verify: cargo test",
]
);
assert_eq!(risk(&["rm".into(), "-rf".into(), "build".into()]), None);
assert_eq!(
risk(&["sudo".into(), "make".into()]),
Some("runs with elevated rights")
);
Ok(())
}
#[test]
fn stored_legacy_duplicate_flags_are_read() -> Result<()> {
let quality: Quality = serde_json::from_value(json!({"python_duplicates": false}))?;
assert_eq!(quality.python_duplicates, DuplicateMode::Off);
assert!(serde_json::from_value::<Quality>(json!({"python_duplicates": "maybe"})).is_err());
Ok(())
}
}