use crate::plan::Plan;
use anyhow::{anyhow, bail, Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::{Component, Path},
};
pub const STATE_SQL: &str = include_str!("../specs/state.sql");
const ROLES: &str = include_str!("../specs/roles.yaml");
const REQUIRED_ROLES: [&str; 3] = ["build", "plan", "review"];
const OPTIONAL_ROLES: [&str; 2] = ["specify", "verify"];
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct Catalog {
schema_version: u32,
roles: BTreeMap<String, Role>,
}
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct Role {
instructions: String,
output_schema: String,
purpose: String,
file_access: String,
#[serde(default)]
handoff_prompts: BTreeMap<String, String>,
integrated_prompt: Option<String>,
}
pub fn builtin_asset(name: &str) -> Result<String> {
Ok(match name {
"roles.yaml" => ROLES,
"planner-output.schema.json" => {
include_str!("../specs/planner-output.schema.json")
}
"outcome.schema.json" => include_str!("../specs/outcome.schema.json"),
"prompts/plan.md" => include_str!("../specs/prompts/plan.md"),
"prompts/build.md" => include_str!("../specs/prompts/build.md"),
"prompts/review.md" => include_str!("../specs/prompts/review.md"),
"verification.schema.json" => include_str!("../specs/verification.schema.json"),
"prompts/verify.md" => include_str!("../specs/prompts/verify.md"),
"specify-output.schema.json" => include_str!("../specs/specify-output.schema.json"),
"prompts/specify.md" => include_str!("../specs/prompts/specify.md"),
"prompts/build-worktree.md" => {
include_str!("../specs/prompts/build-worktree.md")
}
"prompts/build-commit.md" => include_str!("../specs/prompts/build-commit.md"),
"prompts/review-integrated.md" => {
include_str!("../specs/prompts/review-integrated.md")
}
_ => bail!("unknown built-in asset: {name}"),
}
.into())
}
pub fn profile(path: Option<&Path>) -> Result<Value> {
let source = match path {
Some(p) => fs::read_to_string(p)?,
None => ROLES.into(),
};
let catalog: Catalog = serde_yaml_ng::from_str(&source).context("invalid roles YAML")?;
let names: BTreeSet<&str> = catalog.roles.keys().map(String::as_str).collect();
if catalog.schema_version != 1
|| !REQUIRED_ROLES.iter().all(|name| names.contains(name))
|| names
.iter()
.any(|name| !REQUIRED_ROLES.contains(name) && !OPTIONAL_ROLES.contains(name))
{
bail!("roles YAML needs schema_version 1 and build, plan and review (specify and verify are optional)");
}
let asset = |name: &str| -> Result<String> {
scope_path(name)?;
match path {
Some(p) => fs::read_to_string(p.parent().unwrap_or(Path::new(".")).join(name))
.with_context(|| format!("cannot read role asset {name}")),
None => builtin_asset(name),
}
};
let mut result = serde_json::Map::new();
for (name, role) in catalog.roles {
let expected_access = if name == "build" {
"assigned_scope"
} else {
"read_only"
};
if role.file_access != expected_access || role.purpose.trim().is_empty() {
bail!("invalid access or purpose for role {name}");
}
let expected_schema = match name.as_str() {
"plan" => "planner-output.schema.json",
"verify" => "verification.schema.json",
"specify" => "specify-output.schema.json",
_ => "outcome.schema.json",
};
if role.output_schema != expected_schema
&& !(name == "plan" && role.output_schema == "plan.schema.json")
{
bail!("role {name} must use {expected_schema}");
}
if name == "build"
&& role
.handoff_prompts
.keys()
.map(String::as_str)
.ne(["commit", "worktree"])
{
bail!("build role needs commit and worktree handoff prompts");
}
let handoff = role
.handoff_prompts
.iter()
.map(|(key, value)| Ok((key.clone(), asset(value)?)))
.collect::<Result<BTreeMap<_, _>>>()?;
let integrated = role.integrated_prompt.as_deref().map(asset).transpose()?;
result.insert(name, json!({
"instructions": asset(&role.instructions)?, "schema": builtin_asset(expected_schema)?,
"handoff_prompts": handoff, "integrated_prompt": integrated,
"purpose": role.purpose, "file_access": role.file_access,
}));
}
let builtin: Catalog = serde_yaml_ng::from_str(ROLES)?;
for name in OPTIONAL_ROLES {
if result.contains_key(name) {
continue;
}
let role = &builtin.roles[name];
result.insert(
name.into(),
json!({
"instructions": builtin_asset(&role.instructions)?,
"schema": builtin_asset(&role.output_schema)?,
"handoff_prompts": {}, "integrated_prompt": null,
"purpose": role.purpose, "file_access": role.file_access,
}),
);
}
Ok(json!({"schema_version": 1, "roles": result}))
}
pub fn count(n: usize, noun: &str) -> String {
format!("{n} {noun}{}", if n == 1 { "" } else { "s" })
}
pub fn string_or_empty(value: &Value) -> &str {
value.as_str().unwrap_or("")
}
pub fn array_or_empty(value: &Value) -> &[Value] {
value.as_array().map(Vec::as_slice).unwrap_or(&[])
}
pub fn text<'a>(value: &'a Value, label: &str) -> Result<&'a str> {
value
.as_str()
.filter(|s| !s.trim().is_empty())
.ok_or_else(|| anyhow!("{label} must be a nonempty string"))
}
pub fn identifier(value: &str, label: &str) -> Result<()> {
if value.is_empty()
|| value.len() > 64
|| !value.as_bytes()[0].is_ascii_alphanumeric()
|| !value
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
{
bail!("{label} must contain 1–64 letters, digits, underscores or hyphens");
}
Ok(())
}
pub fn scope_path(path: &str) -> Result<()> {
let normalized = Path::new(path)
.components()
.map(|part| match part {
Component::Normal(value) if value != ".git" => value.to_str(),
_ => None,
})
.collect::<Option<Vec<_>>>();
if path.is_empty()
|| path.contains(['\\', '\0'])
|| normalized.map(|p| p.join("/")).as_deref() != Some(path)
{
bail!("invalid repository-relative path: {path:?}");
}
Ok(())
}
pub fn owns<S: AsRef<str>>(path: &str, scopes: &[S]) -> bool {
scopes.iter().any(|scope| {
let scope = scope.as_ref();
path == scope
|| path
.strip_prefix(scope)
.is_some_and(|tail| tail.starts_with('/'))
})
}
pub fn overlaps<S: AsRef<str>>(left: &[S], right: &[S]) -> bool {
left.iter().any(|path| owns(path.as_ref(), right))
|| right.iter().any(|path| owns(path.as_ref(), left))
}
fn criteria(task: &Value) -> Result<Vec<Value>> {
let mut ids = BTreeSet::new();
array_or_empty(&task["acceptance"])
.iter()
.enumerate()
.map(|(index, item)| {
let (id, message) = if item.is_object() {
fields(item, "acceptance item", &["id", "text", "refs"])?;
let id = text(&item["id"], "acceptance id")?;
identifier(id, "acceptance id")?;
(id.into(), text(&item["text"], "acceptance text")?)
} else {
(format!("AC-{}", index + 1), text(item, "acceptance text")?)
};
if !ids.insert(id.clone()) {
bail!("duplicate acceptance id {id}");
}
let mut criterion = json!({"id": id, "text": message});
let none = json!([]);
let refs = strings(item.get("refs").unwrap_or(&none), "acceptance refs", false)?;
for reference in array_or_empty(&refs) {
let reference = string_or_empty(reference);
if !spec_reference(reference) {
bail!("acceptance ref {reference:?} must name a spec requirement (FR-1) or success criterion (SC-1)");
}
}
if !array_or_empty(&refs).is_empty() {
criterion["refs"] = refs;
}
Ok(criterion)
})
.collect()
}
fn spec_reference(id: &str) -> bool {
["FR-", "SC-"].iter().any(|prefix| {
id.strip_prefix(prefix).is_some_and(|digits| {
(1..=4).contains(&digits.len()) && digits.bytes().all(|c| c.is_ascii_digit())
})
})
}
pub fn fields(value: &Value, label: &str, allowed: &[&str]) -> Result<()> {
let object = value
.as_object()
.with_context(|| format!("{label} must be an object"))?;
if let Some(key) = object.keys().find(|key| !allowed.contains(&key.as_str())) {
bail!("unknown field {key:?} in {label}");
}
Ok(())
}
fn strings(value: &Value, label: &str, required: bool) -> Result<Value> {
let values = value
.as_array()
.filter(|v| !required || !v.is_empty())
.ok_or_else(|| {
anyhow!(
"{label} must be a list{} ",
if required {
" with at least one entry"
} else {
""
}
)
})?;
for item in values {
text(item, label)?;
}
Ok(value.clone())
}
fn commands(value: &Value, label: &str, required: bool) -> Result<Value> {
let values = value
.as_array()
.filter(|v| !required || !v.is_empty())
.ok_or_else(|| anyhow!("{label} must be an argv list"))?;
for item in values {
strings(item, label, true)?;
}
Ok(value.clone())
}
fn optional_list<'a>(object: &'a Value, key: &str, empty: &'a Value) -> &'a Value {
object.get(key).unwrap_or(empty)
}
pub fn quality(plan: &Value) -> Result<Value> {
let mut output = json!({"python_duplicates": "warn", "ignore_paths": [], "checks": [], "review": false,
"verify_findings": false});
if let Some(policy) = plan.get("quality") {
let fields = policy
.as_object()
.ok_or_else(|| anyhow!("quality must be an object"))?;
for (key, value) in fields {
output[key] = match key.as_str() {
"python_duplicates" => match value {
Value::Bool(true) => json!("block"),
Value::Bool(false) => json!("off"),
Value::String(mode) if matches!(mode.as_str(), "off" | "warn" | "block") => {
value.clone()
}
_ => bail!("quality.python_duplicates must be off, warn or block"),
},
"review" | "verify_findings" if value.is_boolean() => value.clone(),
"ignore_paths" => {
let paths = strings(value, key, false)?;
for path in array_or_empty(&paths) {
scope_path(string_or_empty(path))?;
}
paths
}
"checks" => commands(value, key, false)?,
_ => bail!("invalid quality option {key}"),
};
}
}
Ok(output)
}
pub fn validate_version(value: &Value) -> Result<()> {
if value
.get("schema_version")
.is_some_and(|version| version.as_u64() != Some(1))
{
bail!("unsupported plan schema_version; expected 1");
}
Ok(())
}
pub fn validate_plan(raw: Value) -> Result<Value> {
fields(
&raw,
"plan",
&[
"schema_version",
"goal",
"tasks",
"setup",
"integration_verify",
"final_verify",
"questions",
"quality",
"spec",
"assumptions",
],
)?;
validate_version(&raw)?;
let empty = json!([]);
if !array_or_empty(&strings(
optional_list(&raw, "questions", &empty),
"questions",
false,
)?)
.is_empty()
{
bail!("the draft has unresolved questions; revise it before running");
}
let tasks = raw["tasks"]
.as_array()
.filter(|items| !items.is_empty())
.ok_or_else(|| anyhow!("tasks must be a nonempty list"))?;
let mut known = BTreeSet::new();
for task in tasks {
fields(
task,
"task",
&[
"id",
"goal",
"title",
"depends",
"owns",
"acceptance",
"setup",
"verify",
"dependency_context",
"related_to",
],
)?;
let id = text(&task["id"], "task id")?;
identifier(id, "task id")?;
if !known.insert(id) {
bail!("duplicate task id {id}");
}
}
let mut normalized = Vec::new();
for task in tasks {
let id = string_or_empty(&task["id"]);
let owned = strings(&task["owns"], "owns", true)?;
for path in array_or_empty(&owned) {
scope_path(string_or_empty(path))?;
}
let depends = strings(optional_list(task, "depends", &empty), "depends", false)?;
for dep in array_or_empty(&depends) {
if !known.contains(string_or_empty(dep)) {
bail!("{id} has unknown dependencies: {}", string_or_empty(dep));
}
}
if !task["acceptance"].is_array() {
bail!("{id}.acceptance must be a nonempty list");
}
let acceptance = criteria(task)?;
if acceptance.is_empty() {
bail!("{id}.acceptance must be a nonempty list");
}
let acceptance: Vec<Value> = array_or_empty(&task["acceptance"])
.iter()
.zip(acceptance)
.map(|(original, item)| {
if original.is_object() {
item
} else {
item["text"].clone()
}
})
.collect();
let mut output = json!({
"id": id, "goal": text(&task["goal"], "task goal")?, "depends": depends, "owns": owned,
"acceptance": acceptance, "setup": commands(optional_list(task, "setup", &empty), "setup", false)?,
"verify": commands(&task["verify"], "verify", true)?,
});
if let Some(title) = task.get("title") {
output["title"] = json!(text(title, "title")?);
}
for (field, explanation) in [
("dependency_context", "needed_for"),
("related_to", "reason"),
] {
let Some(value) = task.get(field) else {
continue;
};
let relations = value
.as_array()
.ok_or_else(|| anyhow!("{id}.{field} must be a list"))?;
let mut seen = BTreeSet::new();
let mut details = Vec::new();
for relation in relations {
fields(
relation,
&format!("{id}.{field}"),
&["task_id", explanation, "refs"],
)?;
let key = text(&relation["task_id"], field)?;
let is_dep = array_or_empty(&depends)
.iter()
.any(|dep| string_or_empty(dep) == key);
if !known.contains(key)
|| key == id
|| !seen.insert(key)
|| is_dep != (field == "dependency_context")
{
bail!("{id}.{field} has invalid relation to {key}");
}
let refs = strings(optional_list(relation, "refs", &empty), "refs", false)?;
for path in array_or_empty(&refs) {
scope_path(string_or_empty(path))?;
}
details.push(json!({"task_id": key, (explanation): text(&relation[explanation], explanation)?, "refs": refs}));
}
if !details.is_empty() {
output[field] = json!(details);
}
}
normalized.push(output);
}
let mut unresolved: BTreeSet<_> = known;
while !unresolved.is_empty() {
let ready: Vec<_> = normalized
.iter()
.filter(|task| {
unresolved.contains(string_or_empty(&task["id"]))
&& array_or_empty(&task["depends"])
.iter()
.all(|dep| !unresolved.contains(string_or_empty(dep)))
})
.map(|task| string_or_empty(&task["id"]))
.collect();
if ready.is_empty() {
bail!("dependency cycle affects: {unresolved:?}");
}
for id in ready {
unresolved.remove(id);
}
}
let mut result = json!({
"goal": text(&raw["goal"], "goal")?, "tasks": normalized,
"setup": commands(optional_list(&raw, "setup", &empty), "setup", false)?,
"integration_verify": commands(optional_list(&raw, "integration_verify", &empty), "integration_verify", false)?,
"final_verify": commands(&raw["final_verify"], "final_verify", true)?,
});
if raw.get("quality").is_some() {
result["quality"] = quality(&raw)?;
}
if raw.get("schema_version").is_some() {
result["schema_version"] = json!(1);
}
let referenced = normalized.iter().any(|task| {
array_or_empty(&task["acceptance"])
.iter()
.any(|item| item.get("refs").is_some())
});
let assumptions = assumptions(optional_list(&raw, "assumptions", &empty))?;
if !assumptions.is_empty() {
result["assumptions"] = json!(assumptions);
}
match raw.get("spec") {
Some(spec) => result["spec"] = spec_ref(spec)?,
None if referenced => bail!("acceptance refs need the plan's spec field"),
None => {}
}
Ok(result)
}
fn assumptions(value: &Value) -> Result<Vec<Value>> {
let items = value
.as_array()
.ok_or_else(|| anyhow!("assumptions must be a list"))?;
items
.iter()
.map(|item| {
fields(item, "assumption", &["text", "impact", "if_wrong"])?;
let impact = text(&item["impact"], "assumption impact")?;
if !["high", "medium", "low"].contains(&impact) {
bail!("assumption impact must be high, medium or low");
}
Ok(
json!({"text": text(&item["text"], "assumption text")?, "impact": impact,
"if_wrong": text(&item["if_wrong"], "assumption if_wrong")?}),
)
})
.collect()
}
fn spec_ref(spec: &Value) -> Result<Value> {
fields(spec, "spec", &["path", "digest", "stories"])?;
let digest = text(&spec["digest"], "spec digest")?;
if !digest.starts_with("sha256:") {
bail!("spec digest must start with sha256:");
}
let stories = strings(&spec["stories"], "spec stories", true)?;
Ok(json!({"path": text(&spec["path"], "spec path")?, "digest": digest, "stories": stories}))
}
pub fn load_plan(path: &Path) -> Result<Plan> {
let input =
fs::read_to_string(path).with_context(|| format!("cannot read plan {}", path.display()))?;
let raw = match path.extension().and_then(|value| value.to_str()) {
Some("yaml" | "yml") => serde_yaml_ng::from_str(&input).context("invalid YAML plan")?,
_ => serde_json::from_str(&input).context("invalid JSON plan")?,
};
Plan::from_value(validate_plan(raw)?)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn duplicate_mode_defaults_to_warn_and_maps_legacy_booleans() -> Result<()> {
assert_eq!(quality(&json!({}))?["python_duplicates"], "warn");
for (input, expected) in [
(json!(true), "block"),
(json!(false), "off"),
(json!("warn"), "warn"),
(json!("block"), "block"),
(json!("off"), "off"),
] {
let policy = quality(&json!({"quality":{"python_duplicates":input}}))?;
assert_eq!(policy["python_duplicates"], expected);
}
assert!(quality(&json!({"quality":{"python_duplicates":"maybe"}})).is_err());
assert!(quality(&json!({"quality":{"unknown":true}})).is_err());
Ok(())
}
#[test]
fn scope_paths_stay_inside_the_repository() {
for good in ["src", "src/a.txt", "docs/guide.md"] {
assert!(scope_path(good).is_ok(), "{good}");
}
for bad in [
"",
"/etc",
"../x",
"a/../b",
"./a",
".git",
"sub/.git/config",
"a\\b",
"a//b",
] {
assert!(scope_path(bad).is_err(), "{bad}");
}
}
#[test]
fn ownership_uses_path_boundaries() {
let scope = ["src/app"];
assert!(owns("src/app", &scope));
assert!(owns("src/app/main.rs", &scope));
assert!(!owns("src/application.rs", &scope));
assert!(overlaps(&["src"], &["src/a.txt"]));
assert!(!overlaps(&["src/a"], &["src/b"]));
}
}