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");
#[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"),
"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")?;
if catalog.schema_version != 1
|| catalog
.roles
.keys()
.map(String::as_str)
.ne(["build", "plan", "review"])
{
bail!("roles YAML needs schema_version 1 and build, plan and review");
}
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 = if name == "plan" {
"planner-output.schema.json"
} else {
"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,
}));
}
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(path: &str, paths: &Value) -> bool {
array_or_empty(paths).iter().any(|item| {
let scope = string_or_empty(item);
path == scope
|| path
.strip_prefix(scope)
.is_some_and(|tail| tail.starts_with('/'))
})
}
pub fn overlaps(left: &Value, right: &Value) -> bool {
array_or_empty(left)
.iter()
.any(|p| owns(string_or_empty(p), right))
|| array_or_empty(right)
.iter()
.any(|p| owns(string_or_empty(p), left))
}
pub 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"])?;
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}");
}
Ok(json!({"id": id, "text": message}))
})
.collect()
}
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});
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" 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",
],
)?;
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);
}
Ok(result)
}
pub fn load_plan(path: &Path) -> Result<Value> {
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")?,
};
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 = json!(["src/app"]);
assert!(owns("src/app", &scope));
assert!(owns("src/app/main.rs", &scope));
assert!(!owns("src/application.rs", &scope));
assert!(overlaps(&json!(["src"]), &json!(["src/a.txt"])));
assert!(!overlaps(&json!(["src/a"]), &json!(["src/b"])));
}
}