use std::{
collections::{HashMap, HashSet},
path::Path,
};
use serde::Serialize;
use crate::{
domain::validate_task_path,
error::{TaskError, ValidationError},
graph::TaskGraph,
identity::{TaskIdentity, TaskReference, is_valid_local_id},
markdown::{has_section, has_unchecked_checklist_item},
model::{Priority, SortBy, Task, TaskStatus},
project::TaskProject,
taxonomy::{is_milestone_type, validate_stored_task, validate_tag},
};
mod candidate;
use candidate::validate_candidate;
pub(crate) use candidate::{CandidateOverrides, CandidateScope, TaskContentOverride};
pub(crate) const RULE_IDS: &[&str] = &[
"CORE-LIBRARY",
"PROVIDER-ACCESS",
"SESSION-BOUNDARY",
"ACTOR-LONG-WORK",
"PIPELINE-TRANSFORMS",
"WIRE-SAFE-EXTENSIONS",
"SEMANTIC-EXTENSION-OUTPUT",
"CORE-MECHANICS-BUILTIN",
];
#[derive(Debug, Clone, Default)]
pub struct TaskFilter {
pub status: Option<TaskStatus>,
pub priority: Option<Priority>,
pub domain: Option<String>,
pub parent: Option<TaskIdentity>,
pub milestone: Option<String>,
pub tag: Option<String>,
pub blocked: bool,
}
#[derive(Debug, Clone)]
pub struct ValidationReport {
pub tasks: Vec<Task>,
pub errors: Vec<ValidationError>,
pub warnings: Vec<ValidationWarning>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ValidationWarning {
pub code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
pub message: String,
pub context: serde_json::Value,
}
#[derive(Debug, Clone)]
pub struct ValidatedRepository {
pub tasks: Vec<Task>,
pub warnings: Vec<ValidationWarning>,
}
impl std::ops::Deref for ValidatedRepository {
type Target = [Task];
fn deref(&self) -> &Self::Target {
&self.tasks
}
}
impl IntoIterator for ValidatedRepository {
type Item = Task;
type IntoIter = std::vec::IntoIter<Task>;
fn into_iter(self) -> Self::IntoIter {
self.tasks.into_iter()
}
}
impl<'a> IntoIterator for &'a ValidatedRepository {
type Item = &'a Task;
type IntoIter = std::slice::Iter<'a, Task>;
fn into_iter(self) -> Self::IntoIter {
self.tasks.iter()
}
}
pub fn validate_repo(project: &TaskProject) -> Result<ValidationReport, TaskError> {
validate_candidate(
project,
CandidateOverrides::default(),
CandidateScope::Repository,
)
}
pub(crate) fn validate_task_candidate(
project: &TaskProject,
path: &Path,
content: &str,
scope: CandidateScope,
) -> Result<ValidationReport, TaskError> {
validate_candidate(
project,
CandidateOverrides {
task: Some(TaskContentOverride { path, content }),
policy: None,
},
scope,
)
}
pub(crate) fn validate_policy_candidate(
project: &TaskProject,
policy: &crate::project::ProjectPolicy,
) -> Result<ValidationReport, TaskError> {
validate_candidate(
project,
CandidateOverrides {
task: None,
policy: Some(policy),
},
CandidateScope::Repository,
)
}
pub fn require_valid_report(report: ValidationReport) -> Result<ValidatedRepository, TaskError> {
if report.errors.is_empty() {
Ok(ValidatedRepository {
tasks: report.tasks,
warnings: report.warnings,
})
} else {
Err(TaskError::Validation(report.errors))
}
}
pub fn filter_tasks(
project: &TaskProject,
tasks: &[Task],
graph: &TaskGraph<'_>,
filter: &TaskFilter,
sort_by: SortBy,
) -> Result<Vec<Task>, TaskError> {
if let Some(tag) = &filter.tag {
validate_tag(project, tag, "tag", None, None)?;
}
let mut tasks: Vec<Task> = tasks
.iter()
.filter(|task| {
let identity = task.identity();
filter
.status
.is_none_or(|status| task.metadata.status == status)
&& filter
.priority
.is_none_or(|priority| task.metadata.priority == priority)
&& filter
.domain
.as_ref()
.is_none_or(|domain| &task.domain == domain)
&& filter
.parent
.as_ref()
.is_none_or(|parent| graph.parent_identity(&identity) == Some(parent))
&& filter
.milestone
.as_ref()
.is_none_or(|milestone| task.metadata.milestone.as_ref() == Some(milestone))
&& filter
.tag
.as_ref()
.is_none_or(|tag| task.metadata.tags.iter().any(|value| value == tag))
&& (!filter.blocked || task.metadata.status == TaskStatus::Blocked)
})
.cloned()
.collect();
match sort_by {
SortBy::Status => tasks.sort_by_key(|task| status_order(task.metadata.status)),
SortBy::Priority => tasks.sort_by_key(|task| priority_order(task.metadata.priority)),
SortBy::Id => tasks.sort_by(|left, right| {
left.metadata
.id
.cmp(&right.metadata.id)
.then_with(|| left.domain.cmp(&right.domain))
}),
SortBy::Domain => tasks.sort_by(|left, right| {
left.domain
.cmp(&right.domain)
.then_with(|| left.metadata.id.cmp(&right.metadata.id))
}),
}
Ok(tasks)
}
fn validate_single_task(project: &TaskProject, task: &Task, errors: &mut Vec<ValidationError>) {
let path = &task.path;
let metadata = &task.metadata;
if !is_valid_local_id(&metadata.id) {
errors.push(ValidationError::at(
path,
format!("invalid id {}; expected PREFIX-NUMBER", metadata.id),
));
}
if metadata.title.chars().count() < 5 {
errors.push(ValidationError::at(
path,
"title must be at least 5 characters",
));
}
if let Some(parent) = &metadata.parent
&& let Err(error) = TaskReference::parse(parent)
{
errors.push(ValidationError::at(
path,
format!("invalid parent reference {parent}: {}", error.constraint()),
));
}
for depends_on in &metadata.depends_on {
if let Err(error) = TaskReference::parse(depends_on) {
errors.push(ValidationError::at(
path,
format!(
"invalid dependency reference {depends_on}: {}",
error.constraint()
),
));
}
}
for rule in &metadata.rules {
if !RULE_IDS.contains(&rule.as_str()) {
errors.push(ValidationError::at(path, format!("unknown rule id {rule}")));
}
}
let mut seen_rules = HashSet::new();
for rule in &metadata.rules {
if !seen_rules.insert(rule) {
errors.push(ValidationError::at(
path,
format!("duplicate rule id {rule}"),
));
}
}
if let Some(impact) = &metadata.impact
&& impact.chars().count() < 10
{
errors.push(ValidationError::at(
path,
"impact must be at least 10 characters when present",
));
}
if let Some(last_updated) = &metadata.last_updated
&& !is_valid_iso_date(last_updated)
{
errors.push(ValidationError::at(
path,
"last_updated must use YYYY-MM-DD format",
));
}
validate_task_path(project, task, errors);
validate_stored_task(project, task, errors);
}
fn validate_body(
project: &TaskProject,
task: &Task,
content: &str,
errors: &mut Vec<ValidationError>,
) {
let metadata = &task.metadata;
if metadata.status == TaskStatus::Blocked && !has_section(content, "Blocked Reason") {
errors.push(ValidationError::at(
&task.path,
"blocked tasks must include ## Blocked Reason",
));
}
if matches!(metadata.status, TaskStatus::Deferred | TaskStatus::Obsolete) {
if !has_section(content, "Rationale") {
errors.push(ValidationError::at(
&task.path,
"deferred and obsolete tasks must include ## Rationale",
));
}
return;
}
let Some(type_policy) = project.policy().task_type(metadata.task_type.as_str()) else {
return;
};
let heading = type_policy.criteria().heading();
if !has_section(content, heading) {
errors.push(ValidationError::at(
&task.path,
format!("{} tasks must include ## {heading}", metadata.task_type),
));
}
if metadata.status == TaskStatus::Done && has_unchecked_checklist_item(content, heading) {
errors.push(ValidationError::at(
&task.path,
format!("done tasks must not have unchecked ## {heading} items"),
));
}
}
fn validate_milestone_references(
project: &TaskProject,
tasks: &[Task],
errors: &mut Vec<ValidationError>,
) {
let mut milestone_counts: HashMap<&str, usize> = HashMap::new();
for task in tasks {
if is_milestone_type(project, &task.metadata.task_type) {
if let Some(milestone) = task
.metadata
.milestone
.as_deref()
.filter(|value| !value.trim().is_empty())
{
*milestone_counts.entry(milestone).or_default() += 1;
} else {
errors.push(ValidationError::at(
&task.path,
"milestone-role tasks must include a non-empty milestone value",
));
}
}
}
for task in tasks {
let Some(milestone) = &task.metadata.milestone else {
continue;
};
match milestone_counts
.get(milestone.as_str())
.copied()
.unwrap_or(0)
{
1 => {}
0 => errors.push(ValidationError::at(
&task.path,
format!("milestone {milestone} must match exactly one milestone-role task"),
)),
_ => errors.push(ValidationError::at(
&task.path,
format!("milestone {milestone} references multiple milestone tasks"),
)),
}
}
}
fn domain_for_path(root: &Path, path: &Path) -> Option<String> {
path.strip_prefix(root)
.ok()?
.components()
.nth(1)?
.as_os_str()
.to_str()
.map(str::to_string)
}
fn is_valid_iso_date(value: &str) -> bool {
let parts: Vec<_> = value.split('-').collect();
if parts.len() != 3 || parts[0].len() != 4 || parts[1].len() != 2 || parts[2].len() != 2 {
return false;
}
let Ok(year) = parts[0].parse::<u16>() else {
return false;
};
let Ok(month) = parts[1].parse::<u8>() else {
return false;
};
let Ok(day) = parts[2].parse::<u8>() else {
return false;
};
let max_day = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if is_leap_year(year) => 29,
2 => 28,
_ => return false,
};
day >= 1 && day <= max_day
}
fn is_leap_year(year: u16) -> bool {
(year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
}
fn status_order(status: TaskStatus) -> u8 {
match status {
TaskStatus::Done => 0,
TaskStatus::InProgress => 1,
TaskStatus::Blocked => 2,
TaskStatus::ToDo => 3,
TaskStatus::Deferred => 4,
TaskStatus::Obsolete => 5,
}
}
fn priority_order(priority: Priority) -> u8 {
match priority {
Priority::High => 0,
Priority::Medium => 1,
Priority::Low => 2,
}
}
#[cfg(test)]
mod tests {
use std::{fs, path::Path};
use tempfile::TempDir;
use super::{TaskFilter, ValidationReport, filter_tasks, validate_repo as validate_project};
use crate::{
error::TaskError,
graph::TaskGraph,
identity::TaskIdentity,
model::{Priority, SortBy, TaskStatus},
project::TaskProject,
};
fn validate_repo(root: &Path) -> Result<ValidationReport, TaskError> {
let project = TaskProject::open(root)?;
validate_project(&project)
}
#[test]
fn validate_succeeds_for_minimal_task_tree() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"",
);
let report = validate_repo(temp.path()).expect("repo should validate");
assert!(report.errors.is_empty());
assert_eq!(report.tasks.len(), 1);
}
#[test]
fn validate_rejects_duplicate_ids() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"",
);
write_task(
temp.path(),
"core/CORE-001-location-cache.md",
"CORE-001",
"Location cache",
"Done",
"Medium",
"",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(
report
.errors
.iter()
.any(|error| error.message.contains("duplicate task id core:CORE-001"))
);
}
#[test]
fn validate_rejects_orphaned_parent() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-002-location-routing.md",
"CORE-002",
"Location routing",
"To Do",
"High",
"parent: CORE-001\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("parent CORE-001 does not reference a task in domain core")
}));
}
#[test]
fn validate_rejects_filename_without_id_prefix() {
let temp = task_repo();
write_task(
temp.path(),
"core/location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("file name must start with CORE-001-")
}));
}
#[test]
fn validate_rejects_invalid_last_updated() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"last_updated: 2026-02-30\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("last_updated must use YYYY-MM-DD format")
}));
}
#[test]
fn filter_matches_status_priority_domain_parent_and_tag() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"In Progress",
"High",
"tags: [location, routing]\n",
);
write_task(
temp.path(),
"core/VFS-001-provider-routing.md",
"VFS-001",
"Provider routing",
"To Do",
"Medium",
"parent: CORE-001\ntags: [provider]\n",
);
let report = validate_repo(temp.path()).expect("repo should validate");
assert!(report.errors.is_empty());
let project = TaskProject::open(temp.path()).expect("project should open");
let graph = TaskGraph::new(&project, &report.tasks).expect("graph should build");
let filtered = filter_tasks(
&project,
&report.tasks,
&graph,
&TaskFilter {
status: Some(TaskStatus::ToDo),
priority: Some(Priority::Medium),
domain: Some("core".to_string()),
parent: Some(TaskIdentity::new("core", "CORE-001").expect("valid identity")),
milestone: None,
tag: Some("provider".to_string()),
blocked: false,
},
SortBy::Id,
)
.expect("filter should validate");
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].metadata.id, "VFS-001");
}
#[test]
fn validate_rejects_missing_type() {
let temp = task_repo();
fs::write(
temp.path().join(".tasks/core/CORE-001-location-routing.md"),
"---\nid: CORE-001\ntitle: Location routing\nstatus: To Do\npriority: High\n---\n\n## Acceptance Criteria\n\n- [ ] Works\n",
)
.expect("task should be written");
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(
report
.errors
.iter()
.any(|error| { error.message.contains("missing field `type`") })
);
}
#[test]
fn validate_rejects_missing_acceptance_criteria() {
let temp = task_repo();
fs::write(
temp.path().join(".tasks/core/CORE-001-location-routing.md"),
"---\nid: CORE-001\ntitle: Location routing\nstatus: To Do\npriority: High\ntype: Feature\n---\n",
)
.expect("task should be written");
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("tasks must include ## Acceptance Criteria")
}));
}
#[test]
fn validate_requires_exit_criteria_for_milestones() {
let temp = task_repo();
fs::create_dir_all(temp.path().join(".tasks/milestones"))
.expect("milestone task dir should exist");
fs::write(
temp.path().join(".tasks/milestones/MILESTONE-000-core-contracts.md"),
"---\nid: MILESTONE-000\ntitle: Core contracts\nstatus: To Do\npriority: High\ntype: Milestone\nmilestone: \"0.3.0\"\n---\n",
)
.expect("task should be written");
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("Milestone tasks must include ## Exit Criteria")
}));
}
#[test]
fn validate_accepts_project_milestone_references() {
let temp = task_repo();
write_milestone(temp.path(), "MILESTONE-003", "0.3.0");
write_task(
temp.path(),
"core/CORE-042-timeout-propagation.md",
"CORE-042",
"Timeout propagation",
"To Do",
"High",
"milestone: \"0.3.0\"\n",
);
let report = validate_repo(temp.path()).expect("repo should validate");
assert!(report.errors.is_empty());
}
#[test]
fn validate_rejects_missing_milestone_declaration() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-042-timeout-propagation.md",
"CORE-042",
"Timeout propagation",
"To Do",
"High",
"milestone: \"0.3.0\"\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("milestone 0.3.0 must match exactly one milestone-role task")
}));
}
#[test]
fn validate_rejects_duplicate_milestone_declarations() {
let temp = task_repo();
write_milestone(temp.path(), "MILESTONE-003", "0.3.0");
write_milestone(temp.path(), "MILESTONE-004", "0.3.0");
write_task(
temp.path(),
"core/CORE-042-timeout-propagation.md",
"CORE-042",
"Timeout propagation",
"To Do",
"High",
"milestone: \"0.3.0\"\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("milestone 0.3.0 references multiple milestone tasks")
}));
}
#[test]
fn validate_rejects_milestone_prefix_outside_milestones_dir() {
let temp = task_repo();
fs::write(
temp.path().join(".tasks/core/MILESTONE-003-core-contracts.md"),
"---\nid: MILESTONE-003\ntitle: Core contracts\nstatus: To Do\npriority: High\ntype: Feature\n---\n\n## Acceptance Criteria\n\n- [ ] Works\n",
)
.expect("task should be written");
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("prefix \"MILESTONE\" is not allowed")
}));
}
#[test]
fn validate_rejects_blocked_tasks_without_reason() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-042-timeout-propagation.md",
"CORE-042",
"Timeout propagation",
"Blocked",
"High",
"",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("blocked tasks must include ## Blocked Reason")
}));
}
#[test]
fn validate_rejects_done_tasks_with_unchecked_acceptance() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-042-timeout-propagation.md",
"CORE-042",
"Timeout propagation",
"Done",
"High",
"",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("done tasks must not have unchecked ## Acceptance Criteria items")
}));
}
#[test]
fn validate_requires_rationale_for_deferred_tasks() {
let temp = task_repo();
fs::write(
temp.path().join(".tasks/core/CORE-001-location-routing.md"),
"---\nid: CORE-001\ntitle: Location routing\nstatus: Deferred\npriority: High\ntype: Feature\n---\n",
)
.expect("task should be written");
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error
.message
.contains("deferred and obsolete tasks must include ## Rationale")
}));
}
#[test]
fn validate_rejects_dependency_problems() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"depends_on: [CORE-001, CORE-404, CORE-404]\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(
report
.errors
.iter()
.any(|error| error.message.contains("task cannot depend on itself"))
);
assert!(report.errors.iter().any(|error| {
error
.message
.contains("dependency CORE-404 does not reference a task in domain core")
}));
assert!(report.errors.iter().any(|error| {
error
.message
.contains("duplicate dependency reference CORE-404")
}));
}
#[test]
fn validate_rejects_dependency_cycles() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"depends_on: [CORE-002]\n",
);
write_task(
temp.path(),
"core/CORE-002-location-cache.md",
"CORE-002",
"Location cache",
"To Do",
"High",
"depends_on: [CORE-001]\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(report.errors.iter().any(|error| {
error.message.contains(
"dependency cycle detected: core:CORE-001 -> core:CORE-002 -> core:CORE-001",
)
}));
}
#[test]
fn validate_rejects_unknown_rule_and_short_impact() {
let temp = task_repo();
write_task(
temp.path(),
"core/CORE-001-location-routing.md",
"CORE-001",
"Location routing",
"To Do",
"High",
"rules: [CORE-LIBRARY, UNKNOWN-RULE]\nimpact: short\n",
);
let report = validate_repo(temp.path()).expect("repo should scan");
assert!(
report
.errors
.iter()
.any(|error| error.message.contains("unknown rule id UNKNOWN-RULE"))
);
assert!(report.errors.iter().any(|error| {
error
.message
.contains("impact must be at least 10 characters when present")
}));
}
#[test]
fn validate_accepts_expanded_prefixes() {
let temp = task_repo();
write_task(
temp.path(),
"core/PROTOCOL-001-wire-envelope.md",
"PROTOCOL-001",
"Wire envelope",
"To Do",
"High",
"",
);
write_task(
temp.path(),
"ecosystem/EXT-001-decoration-output.md",
"EXT-001",
"Decoration output",
"To Do",
"High",
"",
);
let report = validate_repo(temp.path()).expect("repo should validate");
assert!(report.errors.is_empty());
}
fn task_repo() -> TempDir {
let temp = tempfile::tempdir().expect("temp dir should be created");
fs::create_dir_all(temp.path().join(".tasks/core")).expect("core task dir should exist");
fs::create_dir_all(temp.path().join(".tasks/app")).expect("app task dir should exist");
fs::create_dir_all(temp.path().join(".tasks/ecosystem"))
.expect("ecosystem task dir should exist");
fs::write(temp.path().join(".tasks/task.schema.json"), "{}")
.expect("schema should be written");
temp
}
fn write_milestone(root: &Path, id: &str, milestone: &str) {
let path = root
.join(".tasks/milestones")
.join(format!("{id}-project-milestone.md"));
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("task parent dir should exist");
}
fs::write(
path,
format!(
"---\nid: {id}\ntitle: Project milestone\nstatus: To Do\npriority: High\ntype: Milestone\nmilestone: \"{milestone}\"\n---\n\n## Exit Criteria\n\n- [ ] Finished\n"
),
)
.expect("milestone should be written");
}
fn write_task(
root: &Path,
relative: &str,
id: &str,
title: &str,
status: &str,
priority: &str,
extra: &str,
) {
let path = root.join(".tasks").join(relative);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("task parent dir should exist");
}
fs::write(
path,
format!(
"---\nid: {id}\ntitle: {title}\nstatus: {status}\npriority: {priority}\ntype: Feature\n{extra}---\n\n## Acceptance Criteria\n\n- [ ] Works\n"
),
)
.expect("task should be written");
}
}