feat(929): delete db/yaml_legacy.rs entirely — CRDT is the sole source of truth

Final 929 sweep: every YAML-shaped helper is gone. No production code
parses or writes YAML front matter anywhere.

Surface removed:
- db/yaml_legacy.rs (FrontMatter/StoryMetadata structs, parse_front_matter,
  set_front_matter_field, yaml_residue marker) — file deleted.
- ItemMeta::from_yaml — deleted; callers pass typed ItemMeta::named(...) or
  ItemMeta::default() and use typed CRDT setters (set_depends_on,
  set_blocked, set_retry_count, set_agent, set_qa_mode, set_review_hold,
  set_item_type, set_epic, set_mergemaster_attempted) for the rest.
- write_coverage_baseline_to_story_file + read_coverage_percent_from_json —
  the coverage_baseline YAML field was write-only (nothing read it back);
  removed along with its caller in agent_tools/lifecycle.rs.
- update_story_in_file's generic `front_matter` HashMap parameter —
  tool_update_story now intercepts every known field name and routes it
  to a typed CRDT setter; unknown keys are rejected with an explicit error
  pointing at the typed setters. The function only takes user_story /
  description sections now.
- All 117 ItemMeta::from_yaml callsites migrated. Where tests previously
  passed a YAML-shaped content blob and relied on the helper to extract
  name/depends_on/blocked/agent/qa, they now pass:
    write_item_with_content(id, stage, content, ItemMeta::named("Foo"))
    crate::crdt_state::set_depends_on(id, &[...])    // when needed
    crate::crdt_state::set_blocked(id, true)         // when needed
    crate::crdt_state::set_agent(id, Some("..."))    // when needed
- write_story_content + write_story_file (test helper) now take an
  explicit `name: Option<&str>` instead of parsing it from content.
- db::ops::move_item_stage stopped re-parsing YAML on every stage
  transition; metadata is read straight from the CRDT view when mirroring
  the row into SQLite.

New CRDT setters added for symmetry:
- crdt_state::set_name (mirrors set_agent — explicit name updates).

cargo fmt --check, clippy --all-targets -- -D warnings, and the
2830-test suite all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Timmy
2026-05-12 20:55:25 +01:00
parent 6c62e0fa31
commit 69d91d7707
58 changed files with 433 additions and 1344 deletions
+1 -1
View File
@@ -60,7 +60,7 @@ pub fn create_bug_file(
}
// Write to database content store and CRDT.
write_story_content(root, &bug_id, "1_backlog", &content);
write_story_content(root, &bug_id, "1_backlog", &content, Some(name));
// Sync depends_on to the typed CRDT register.
crate::crdt_state::set_depends_on(&bug_id, depends_on.unwrap_or(&[]));
+1 -1
View File
@@ -70,7 +70,7 @@ pub fn create_epic_file(
}
// Epics are stored in backlog (no pipeline advancement).
write_story_content(root, &epic_id, "1_backlog", &content);
write_story_content(root, &epic_id, "1_backlog", &content, Some(name));
// Story 933: typed CRDT register for item_type.
crate::crdt_state::set_item_type(&epic_id, Some("epic"));
+1 -1
View File
@@ -56,7 +56,7 @@ pub fn create_refactor_file(
content.push_str("- TBD\n");
// Write to database content store and CRDT.
write_story_content(root, &refactor_id, "1_backlog", &content);
write_story_content(root, &refactor_id, "1_backlog", &content, Some(name));
// Sync depends_on to the typed CRDT register.
crate::crdt_state::set_depends_on(&refactor_id, depends_on.unwrap_or(&[]));
+1 -1
View File
@@ -61,7 +61,7 @@ pub fn create_spike_file(
}
// Write to database content store and CRDT.
write_story_content(root, &spike_id, "1_backlog", &content);
write_story_content(root, &spike_id, "1_backlog", &content, Some(name));
// Sync depends_on to the typed CRDT register.
crate::crdt_state::set_depends_on(&spike_id, depends_on.unwrap_or(&[]));
+19 -57
View File
@@ -3,7 +3,6 @@
use super::bug::{create_bug_file, extract_bug_name_from_content, list_bug_files};
use super::refactor::{create_refactor_file, list_refactor_files};
use super::spike::create_spike_file;
use crate::db::yaml_legacy::parse_front_matter;
use std::fs;
fn setup_git_repo(root: &std::path::Path) {
@@ -50,13 +49,13 @@ fn next_item_number_increments_from_existing_bugs() {
"1_bug_crash",
"1_backlog",
"---\nname: Crash\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Crash\n---\n"),
crate::db::ItemMeta::named("Crash"),
);
crate::db::write_item_with_content(
"3_bug_another",
"1_backlog",
"---\nname: Another\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Another\n---\n"),
crate::db::ItemMeta::named("Another"),
);
assert!(super::super::next_item_number(tmp.path()).unwrap() >= 4);
}
@@ -75,7 +74,7 @@ fn next_item_number_scans_archived_too() {
"5_bug_old",
"5_done",
"---\nname: Old Bug\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Old Bug\n---\n"),
crate::db::ItemMeta::named("Old Bug"),
);
assert!(super::super::next_item_number(tmp.path()).unwrap() >= 6);
}
@@ -98,14 +97,14 @@ fn list_bug_files_excludes_archive_subdir() {
"7001_bug_open",
"1_backlog",
"---\nname: Open Bug\n---\n# Bug 7001: Open Bug\n",
crate::db::ItemMeta::from_yaml("---\nname: Open Bug\n---\n# Bug 7001: Open Bug\n"),
crate::db::ItemMeta::named("Open Bug"),
);
// Bug in done (should NOT appear — list_bug_files only returns Backlog).
crate::db::write_item_with_content(
"7002_bug_closed",
"5_done",
"---\nname: Closed Bug\n---\n# Bug 7002: Closed Bug\n",
crate::db::ItemMeta::from_yaml("---\nname: Closed Bug\n---\n# Bug 7002: Closed Bug\n"),
crate::db::ItemMeta::named("Closed Bug"),
);
let result = list_bug_files(tmp.path()).unwrap();
@@ -125,19 +124,19 @@ fn list_bug_files_sorted_by_id() {
"7013_bug_third",
"1_backlog",
"---\nname: Third\n---\n# Bug 7013: Third\n",
crate::db::ItemMeta::from_yaml("---\nname: Third\n---\n# Bug 7013: Third\n"),
crate::db::ItemMeta::named("Third"),
);
crate::db::write_item_with_content(
"7011_bug_first",
"1_backlog",
"---\nname: First\n---\n# Bug 7011: First\n",
crate::db::ItemMeta::from_yaml("---\nname: First\n---\n# Bug 7011: First\n"),
crate::db::ItemMeta::named("First"),
);
crate::db::write_item_with_content(
"7012_bug_second",
"1_backlog",
"---\nname: Second\n---\n# Bug 7012: Second\n",
crate::db::ItemMeta::from_yaml("---\nname: Second\n---\n# Bug 7012: Second\n"),
crate::db::ItemMeta::named("Second"),
);
let result = list_bug_files(tmp.path()).unwrap();
@@ -349,15 +348,8 @@ fn create_spike_file_with_special_chars_in_name_produces_valid_yaml() {
assert!(result.is_ok(), "create_spike_file failed: {result:?}");
let spike_id = result.unwrap();
let contents = crate::db::read_content(&spike_id)
.or_else(|| {
let backlog = tmp.path().join(".huskies/work/1_backlog");
fs::read_to_string(backlog.join(format!("{spike_id}.md"))).ok()
})
.expect("spike content should exist");
let meta = parse_front_matter(&contents).expect("front matter should be valid YAML");
assert_eq!(meta.name.as_deref(), Some(name));
let view = crate::crdt_state::read_item(&spike_id).expect("CRDT entry should exist");
assert_eq!(view.name(), Some(name));
}
#[test]
@@ -369,7 +361,7 @@ fn create_spike_file_increments_from_existing_items() {
"7050_story_existing",
"1_backlog",
"---\nname: Existing\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Existing\n---\n"),
crate::db::ItemMeta::named("Existing"),
);
let spike_id = create_spike_file(tmp.path(), "My Spike", None, &[], None).unwrap();
@@ -387,7 +379,8 @@ fn create_spike_file_increments_from_existing_items() {
// ── Bug 640: create_bug_file / create_refactor_file depends_on tests ────────
#[test]
fn create_bug_file_with_depends_on_writes_front_matter_array() {
fn create_bug_file_with_depends_on_persists_to_crdt() {
crate::crdt_state::init_for_test();
let tmp = tempfile::tempdir().unwrap();
setup_git_repo(tmp.path());
@@ -403,26 +396,8 @@ fn create_bug_file_with_depends_on_writes_front_matter_array() {
)
.unwrap();
let contents = crate::db::read_content(&bug_id)
.or_else(|| {
let filepath = tmp
.path()
.join(format!(".huskies/work/1_backlog/{bug_id}.md"));
fs::read_to_string(filepath).ok()
})
.expect("bug content should exist");
assert!(
contents.contains("depends_on: [42, 43]"),
"front matter should contain depends_on array: {contents}"
);
assert!(
!contents.contains("depends_on: \"["),
"depends_on must not be quoted string: {contents}"
);
let meta = parse_front_matter(&contents).expect("front matter should be valid YAML");
assert_eq!(meta.depends_on, Some(vec![42, 43]));
let view = crate::crdt_state::read_item(&bug_id).expect("CRDT entry should exist");
assert_eq!(view.depends_on(), &[42, 43]);
}
#[test]
@@ -458,29 +433,16 @@ fn create_bug_file_without_depends_on_omits_field() {
}
#[test]
fn create_refactor_file_with_depends_on_writes_front_matter_array() {
fn create_refactor_file_with_depends_on_persists_to_crdt() {
crate::crdt_state::init_for_test();
let tmp = tempfile::tempdir().unwrap();
setup_git_repo(tmp.path());
let refactor_id =
create_refactor_file(tmp.path(), "Dep Refactor", None, None, Some(&[99])).unwrap();
let contents = crate::db::read_content(&refactor_id)
.or_else(|| {
let filepath = tmp
.path()
.join(format!(".huskies/work/1_backlog/{refactor_id}.md"));
fs::read_to_string(filepath).ok()
})
.expect("refactor content should exist");
assert!(
contents.contains("depends_on: [99]"),
"front matter should contain depends_on array: {contents}"
);
let meta = parse_front_matter(&contents).expect("front matter should be valid YAML");
assert_eq!(meta.depends_on, Some(vec![99]));
let view = crate::crdt_state::read_item(&refactor_id).expect("CRDT entry should exist");
assert_eq!(view.depends_on(), &[99]);
}
#[test]
+1 -4
View File
@@ -16,10 +16,7 @@ pub use story_ops::{
add_criterion_to_file, check_criterion_in_file, create_story_file, edit_criterion_in_file,
remove_criterion_from_file, update_story_in_file,
};
pub use test_results::{
read_test_results_from_story_file, write_coverage_baseline_to_story_file,
write_test_results_to_story_file,
};
pub use test_results::{read_test_results_from_story_file, write_test_results_to_story_file};
pub(crate) use utils::{
create_section_content, next_item_number, read_story_content, replace_or_append_section,
+19 -16
View File
@@ -308,7 +308,10 @@ mod tests {
id,
stage,
&format!("---\nname: {id}\n---\n"),
crate::db::ItemMeta::from_yaml(&format!("---\nname: {id}\n---\n")),
crate::db::ItemMeta {
name: Some((*id).to_string()),
..Default::default()
},
);
}
@@ -353,7 +356,7 @@ mod tests {
"9860_story_test",
"2_current",
"---\nname: Test Story\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Test Story\n---\n# Story\n"),
crate::db::ItemMeta::named("Test Story"),
);
let ctx = crate::http::context::AppContext::new_test(root);
@@ -389,7 +392,7 @@ mod tests {
"9861_story_done",
"2_current",
"---\nname: Done Story\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Done Story\n---\n# Story\n"),
crate::db::ItemMeta::named("Done Story"),
);
let ctx = crate::http::context::AppContext::new_test(root);
@@ -422,7 +425,7 @@ mod tests {
"9862_story_pending",
"2_current",
"---\nname: Pending Story\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Pending Story\n---\n# Story\n"),
crate::db::ItemMeta::named("Pending Story"),
);
let ctx = crate::http::context::AppContext::new_test(root);
@@ -448,20 +451,20 @@ mod tests {
#[test]
fn pipeline_state_includes_depends_on() {
crate::crdt_state::init_for_test();
crate::db::ensure_content_store();
crate::db::write_item_with_content(
"9863_story_dependent",
"1_backlog",
"---\nname: Dependent Story\ndepends_on: [10, 11]\n---\n",
crate::db::ItemMeta::from_yaml(
"---\nname: Dependent Story\ndepends_on: [10, 11]\n---\n",
),
"# Dependent Story\n",
crate::db::ItemMeta::named("Dependent Story"),
);
crate::crdt_state::set_depends_on("9863_story_dependent", &[10, 11]);
crate::db::write_item_with_content(
"9864_story_independent",
"1_backlog",
"---\nname: Independent Story\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Independent Story\n---\n"),
"# Independent Story\n",
crate::db::ItemMeta::named("Independent Story"),
);
let tmp = tempfile::tempdir().unwrap();
@@ -490,13 +493,13 @@ mod tests {
"9870_story_view_upcoming",
"1_backlog",
"---\nname: View Upcoming\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: View Upcoming\n---\n# Story\n"),
crate::db::ItemMeta::named("View Upcoming"),
);
crate::db::write_item_with_content(
"9871_story_worktree",
"1_backlog",
"---\nname: Worktree Orchestration\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Worktree Orchestration\n---\n# Story\n"),
crate::db::ItemMeta::named("Worktree Orchestration"),
);
let tmp = tempfile::tempdir().unwrap();
@@ -523,7 +526,7 @@ mod tests {
"9872_story_example",
"1_backlog",
"---\nname: A Story\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: A Story\n---\n"),
crate::db::ItemMeta::named("A Story"),
);
let tmp = tempfile::tempdir().unwrap();
@@ -539,13 +542,13 @@ mod tests {
"9873_story_todos",
"2_current",
"---\nname: Show TODOs\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Show TODOs\n---\n# Story\n"),
crate::db::ItemMeta::named("Show TODOs"),
);
crate::db::write_item_with_content(
"9874_story_front_matter",
"1_backlog",
"---\nname: Enforce Front Matter\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Enforce Front Matter\n---\n# Story\n"),
crate::db::ItemMeta::named("Enforce Front Matter"),
);
let tmp = tempfile::tempdir().unwrap();
@@ -591,7 +594,7 @@ mod tests {
"9876_story_no_name",
"2_current",
"---\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\n---\n# Story\n"),
crate::db::ItemMeta::default(),
);
let tmp = tempfile::tempdir().unwrap();
+17 -39
View File
@@ -66,7 +66,7 @@ pub fn create_story_file(
content.push_str("- TBD\n");
// Write to database content store and CRDT.
write_story_content(root, &story_id, "1_backlog", &content);
write_story_content(root, &story_id, "1_backlog", &content, Some(name));
// Sync depends_on to the typed CRDT register.
crate::crdt_state::set_depends_on(&story_id, depends_on.unwrap_or(&[]));
@@ -83,7 +83,6 @@ pub fn create_story_file(
#[cfg(test)]
mod tests {
use super::*;
use crate::db::yaml_legacy::parse_front_matter;
use std::fs;
#[allow(dead_code)]
@@ -146,7 +145,7 @@ mod tests {
"36_story_existing",
"1_backlog",
"---\nname: Existing\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Existing\n---\n"),
crate::db::ItemMeta::named("Existing"),
);
let number = super::super::super::next_item_number(tmp.path()).unwrap();
@@ -184,29 +183,24 @@ mod tests {
}
#[test]
fn create_story_with_colon_in_name_produces_valid_yaml() {
fn create_story_with_colon_in_name_persists_to_crdt() {
crate::crdt_state::init_for_test();
let tmp = tempfile::tempdir().unwrap();
let name = "Server-owned agent completion: remove report_completion dependency";
let result = create_story_file(tmp.path(), name, None, None, None, None, false);
assert!(result.is_ok(), "create_story_file failed: {result:?}");
let story_id = result.unwrap();
// Read from content store or filesystem.
let content = crate::db::read_content(&story_id)
.or_else(|| {
let backlog = tmp.path().join(".huskies/work/1_backlog");
fs::read_to_string(backlog.join(format!("{story_id}.md"))).ok()
})
.expect("story content should exist");
let meta = parse_front_matter(&content).expect("front matter should be valid YAML");
assert_eq!(meta.name.as_deref(), Some(name));
let view =
crate::crdt_state::read_item(&story_id).expect("CRDT entry should exist after create");
assert_eq!(view.name(), Some(name));
}
// ── check_criterion_in_file tests ─────────────────────────────────────────
#[test]
fn create_story_with_depends_on_writes_front_matter_array() {
fn create_story_with_depends_on_persists_to_crdt() {
crate::crdt_state::init_for_test();
let tmp = tempfile::tempdir().unwrap();
let story_id = create_story_file(
tmp.path(),
@@ -219,24 +213,9 @@ mod tests {
)
.unwrap();
let contents = crate::db::read_content(&story_id)
.or_else(|| {
let backlog = tmp.path().join(".huskies/work/1_backlog");
fs::read_to_string(backlog.join(format!("{story_id}.md"))).ok()
})
.expect("story content should exist");
assert!(
contents.contains("depends_on: [489]"),
"missing front matter: {contents}"
);
assert!(
!contents.contains("- [ ] depends_on"),
"must not appear as checkbox: {contents}"
);
let meta = parse_front_matter(&contents).expect("front matter should parse");
assert_eq!(meta.depends_on, Some(vec![489]));
let view =
crate::crdt_state::read_item(&story_id).expect("CRDT entry should exist after create");
assert_eq!(view.depends_on(), &[489]);
}
// ── Story 730: numeric-only story IDs ─────────────────────────────────────
@@ -258,19 +237,18 @@ mod tests {
}
#[test]
fn create_story_file_writes_type_field_in_front_matter() {
fn create_story_file_sets_item_type_register() {
crate::crdt_state::init_for_test();
crate::db::ensure_content_store();
let tmp = tempfile::tempdir().unwrap();
let story_id =
create_story_file(tmp.path(), "Type Test Story", None, None, None, None, false)
.unwrap();
let content = crate::db::read_content(&story_id).expect("content must exist");
let meta = crate::db::yaml_legacy::parse_front_matter(&content)
.expect("front matter should be valid");
let view = crate::crdt_state::read_item(&story_id).expect("CRDT entry must exist");
assert_eq!(
meta.item_type.as_deref(),
view.item_type(),
Some("story"),
"front matter must contain type: story"
"CRDT register must be set to story"
);
}
@@ -52,7 +52,7 @@ pub fn check_criterion_in_file(
// Write back to content store.
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &new_str);
write_story_content(project_root, story_id, &stage, &new_str, None);
Ok(())
}
@@ -99,7 +99,7 @@ pub fn remove_criterion_from_file(
}
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &new_str);
write_story_content(project_root, story_id, &stage, &new_str, None);
Ok(())
}
@@ -158,7 +158,7 @@ pub fn edit_criterion_in_file(
}
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &new_str);
write_story_content(project_root, story_id, &stage, &new_str, None);
Ok(())
}
@@ -219,7 +219,7 @@ pub fn add_criterion_to_file(
// Write back to content store.
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &new_str);
write_story_content(project_root, story_id, &stage, &new_str, None);
Ok(())
}
@@ -234,10 +234,7 @@ pub fn add_criterion_to_file(
/// - String → quoted unless it looks like a bool, integer, or inline sequence
#[cfg(test)]
mod tests {
use super::super::update_story_in_file;
use super::*;
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
#[allow(dead_code)]
@@ -437,11 +434,8 @@ mod tests {
## Recommendation\n\n- TBD\n";
setup_story_in_fs(tmp.path(), "100_spike_my_spike", spike_content);
// Convert spike to story by updating the type field.
let mut fields = HashMap::new();
fields.insert("type".to_string(), Value::String("story".to_string()));
update_story_in_file(tmp.path(), "100_spike_my_spike", None, None, Some(&fields))
.expect("converting spike type to story should succeed");
// Convert spike to story by updating the typed item_type CRDT register.
crate::crdt_state::set_item_type("100_spike_my_spike", Some("story"));
// Add three acceptance criteria.
add_criterion_to_file(tmp.path(), "100_spike_my_spike", "First criterion")
+30 -454
View File
@@ -1,7 +1,11 @@
//! update_story_in_file: replaces sections / writes front matter on existing stories.
//! update_story_in_file: replace `## User Story` / `## Description` sections
//! in an existing story's content body.
//!
//! Story 929: the legacy `front_matter` HashMap parameter is gone — every
//! known typed field is intercepted in `tool_update_story` and routed to a
//! typed CRDT setter (set_name, set_agent, set_qa_mode, set_depends_on, …).
//! Any caller still trying to write to YAML front matter is a bug.
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;
#[allow(unused_imports)]
@@ -10,48 +14,6 @@ use super::super::{
slugify_name, story_stage, write_story_content,
};
use crate::db::yaml_legacy::set_front_matter_field;
fn json_value_to_yaml_scalar(value: &Value) -> String {
match value {
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
Value::Array(arr) => {
let items: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
format!("[{}]", items.join(", "))
}
Value::String(s) => yaml_encode_str(s),
// Null and Object are not meaningful as YAML scalars; store as quoted strings.
other => format!(
"\"{}\"",
other
.to_string()
.replace('"', "\\\"")
.replace('\n', " ")
.replace('\r', "")
),
}
}
/// Encode a plain string as a YAML scalar.
///
/// Booleans (`true`/`false`), integers, and inline sequences (`[...]`) are
/// written unquoted. Everything else is quoted to avoid ambiguity.
fn yaml_encode_str(s: &str) -> String {
match s {
"true" | "false" => s.to_string(),
s if s.parse::<i64>().is_ok() => s.to_string(),
s if s.parse::<f64>().is_ok() => s.to_string(),
// YAML inline sequences like [490] or [490, 491] — write unquoted so
// serde_yaml can deserialise them as Vec<u32>.
s if s.starts_with('[') && s.ends_with(']') => s.to_string(),
s => format!(
"\"{}\"",
s.replace('"', "\\\"").replace('\n', " ").replace('\r', "")
),
}
}
/// Update the user story text and/or description in a story.
///
/// At least one of `user_story` or `description` must be provided.
@@ -61,32 +23,13 @@ pub fn update_story_in_file(
story_id: &str,
user_story: Option<&str>,
description: Option<&str>,
front_matter: Option<&HashMap<String, Value>>,
) -> Result<(), String> {
let has_front_matter_updates = front_matter.map(|m| !m.is_empty()).unwrap_or(false);
if user_story.is_none() && description.is_none() && !has_front_matter_updates {
return Err(
"At least one of 'user_story', 'description', or 'front_matter' must be provided."
.to_string(),
);
if user_story.is_none() && description.is_none() {
return Err("At least one of 'user_story' or 'description' must be provided.".to_string());
}
let mut contents = read_story_content(project_root, story_id)?;
if let Some(fields) = front_matter {
if fields.contains_key("acceptance_criteria") {
return Err(
"'acceptance_criteria' is a reserved field managed via the story body \
(use add_criterion / remove_criterion / edit_criterion instead)."
.to_string(),
);
}
for (key, value) in fields {
let yaml_value = json_value_to_yaml_scalar(value);
contents = set_front_matter_field(&contents, key, &yaml_value);
}
}
if let Some(us) = user_story {
contents = match replace_section_content(&contents, "User Story", us) {
Ok(updated) => updated,
@@ -106,7 +49,7 @@ pub fn update_story_in_file(
// Write back to content store.
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &contents);
write_story_content(project_root, story_id, &stage, &contents, None);
Ok(())
}
@@ -114,98 +57,27 @@ pub fn update_story_in_file(
#[cfg(test)]
mod tests {
use super::*;
use crate::db::yaml_legacy::parse_front_matter;
use std::fs;
#[allow(dead_code)]
fn setup_git_repo(root: &std::path::Path) {
std::process::Command::new("git")
.args(["init"])
.current_dir(root)
.output()
.unwrap();
std::process::Command::new("git")
.args(["config", "user.email", "test@test.com"])
.current_dir(root)
.output()
.unwrap();
std::process::Command::new("git")
.args(["config", "user.name", "Test"])
.current_dir(root)
.output()
.unwrap();
std::process::Command::new("git")
.args(["commit", "--allow-empty", "-m", "init"])
.current_dir(root)
.output()
.unwrap();
}
#[allow(dead_code)]
fn story_with_criteria(n: usize) -> String {
let mut s = "---\nname: Test Story\n---\n\n## Acceptance Criteria\n\n".to_string();
for i in 0..n {
s.push_str(&format!("- [ ] Criterion {i}\n"));
}
s
}
/// Helper to set up a story in the filesystem and content store for tests
/// that use check/add criterion.
#[allow(dead_code)]
/// Helper: write a story to both the in-memory content store and the
/// `.huskies/work/2_current/` directory so `read_story_content` picks it up
/// regardless of which read path is used.
fn setup_story_in_fs(root: &std::path::Path, story_id: &str, content: &str) {
let current = root.join(".huskies/work/2_current");
fs::create_dir_all(&current).unwrap();
fs::write(current.join(format!("{story_id}.md")), content).unwrap();
// Also write to the global content store so read_story_content picks up this
// content even when a previous test has left a stale entry for the same ID.
crate::db::ensure_content_store();
crate::db::write_content(story_id, content);
}
// --- create_story integration tests ---
#[test]
fn update_story_acceptance_criteria_in_front_matter_returns_error() {
// Bug 625: passing acceptance_criteria via front_matter must return an
// explicit error rather than silently dropping the value.
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"101_test",
"---\nname: T\n---\n\n## Acceptance Criteria\n\n- [ ] Existing\n",
);
let mut fields = HashMap::new();
fields.insert(
"acceptance_criteria".to_string(),
serde_json::json!(["crit 1", "crit 2"]),
);
let result = update_story_in_file(tmp.path(), "101_test", None, None, Some(&fields));
assert!(result.is_err(), "should fail with reserved-field error");
let err = result.unwrap_err();
assert!(
err.contains("acceptance_criteria"),
"error should name the reserved field: {err}"
);
}
// ── remove_criterion_from_file tests ──────────────────────────────────────
#[test]
fn update_story_replaces_user_story_section() {
let tmp = tempfile::tempdir().unwrap();
let content = "---\nname: T\n---\n\n## User Story\n\nOld text\n\n## Acceptance Criteria\n\n- [ ] AC\n";
let content =
"# Story\n\n## User Story\n\nOld text\n\n## Acceptance Criteria\n\n- [ ] AC\n";
setup_story_in_fs(tmp.path(), "20_test", content);
update_story_in_file(
tmp.path(),
"20_test",
Some("New user story text"),
None,
None,
)
.unwrap();
update_story_in_file(tmp.path(), "20_test", Some("New user story text"), None).unwrap();
let result = read_story_content(tmp.path(), "20_test").unwrap();
assert!(
@@ -222,10 +94,11 @@ mod tests {
#[test]
fn update_story_replaces_description_section() {
let tmp = tempfile::tempdir().unwrap();
let content = "---\nname: T\n---\n\n## Description\n\nOld description\n\n## Acceptance Criteria\n\n- [ ] AC\n";
let content =
"# Story\n\n## Description\n\nOld description\n\n## Acceptance Criteria\n\n- [ ] AC\n";
setup_story_in_fs(tmp.path(), "21_test", content);
update_story_in_file(tmp.path(), "21_test", None, Some("New description"), None).unwrap();
update_story_in_file(tmp.path(), "21_test", None, Some("New description")).unwrap();
let result = read_story_content(tmp.path(), "21_test").unwrap();
assert!(
@@ -241,9 +114,9 @@ mod tests {
#[test]
fn update_story_no_args_returns_error() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "22_test", "---\nname: T\n---\n");
setup_story_in_fs(tmp.path(), "22_test", "# Story\n");
let result = update_story_in_file(tmp.path(), "22_test", None, None, None);
let result = update_story_in_file(tmp.path(), "22_test", None, None);
assert!(result.is_err());
assert!(result.unwrap_err().contains("At least one"));
}
@@ -251,12 +124,10 @@ mod tests {
#[test]
fn update_story_creates_user_story_section_if_missing() {
let tmp = tempfile::tempdir().unwrap();
// Story with no ## User Story section but has ## Acceptance Criteria.
let content = "---\nname: T\n---\n\n## Acceptance Criteria\n\n- [ ] AC\n";
let content = "# Story\n\n## Acceptance Criteria\n\n- [ ] AC\n";
setup_story_in_fs(tmp.path(), "23_test", content);
let result =
update_story_in_file(tmp.path(), "23_test", Some("New user story"), None, None);
let result = update_story_in_file(tmp.path(), "23_test", Some("New user story"), None);
assert!(
result.is_ok(),
"should succeed when section is missing: {result:?}"
@@ -268,7 +139,6 @@ mod tests {
"section should be created"
);
assert!(updated.contains("New user story"), "text should be present");
// Section should appear before Acceptance Criteria.
let pos_us = updated.find("## User Story").unwrap();
let pos_ac = updated.find("## Acceptance Criteria").unwrap();
assert!(
@@ -280,17 +150,12 @@ mod tests {
#[test]
fn update_story_creates_description_section_if_missing() {
let tmp = tempfile::tempdir().unwrap();
// Story with no ## Description section but has ## Acceptance Criteria.
let content = "---\nname: T\n---\n\n## User Story\n\nAs a user...\n\n## Acceptance Criteria\n\n- [ ] AC\n";
let content =
"# Story\n\n## User Story\n\nAs a user...\n\n## Acceptance Criteria\n\n- [ ] AC\n";
setup_story_in_fs(tmp.path(), "32_test", content);
let result = update_story_in_file(
tmp.path(),
"32_test",
None,
Some("New description text"),
None,
);
let result =
update_story_in_file(tmp.path(), "32_test", None, Some("New description text"));
assert!(
result.is_ok(),
"should succeed when section is missing: {result:?}"
@@ -305,7 +170,6 @@ mod tests {
updated.contains("New description text"),
"text should be present"
);
// Section should appear before Acceptance Criteria.
let pos_desc = updated.find("## Description").unwrap();
let pos_ac = updated.find("## Acceptance Criteria").unwrap();
assert!(
@@ -317,17 +181,11 @@ mod tests {
#[test]
fn update_story_creates_description_section_no_ac_section() {
let tmp = tempfile::tempdir().unwrap();
// Story with no ## Description and no ## Acceptance Criteria.
let content = "---\nname: T\n---\n\nSome content here.\n";
let content = "# Story\n\nSome content here.\n";
setup_story_in_fs(tmp.path(), "33_test", content);
let result = update_story_in_file(
tmp.path(),
"33_test",
None,
Some("Appended description"),
None,
);
let result =
update_story_in_file(tmp.path(), "33_test", None, Some("Appended description"));
assert!(
result.is_ok(),
"should succeed even with no Acceptance Criteria: {result:?}"
@@ -343,286 +201,4 @@ mod tests {
"text should be present"
);
}
#[test]
fn update_story_sets_agent_front_matter_field() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"24_test",
"---\nname: T\n---\n\n## User Story\n\nSome story\n",
);
let mut fields = HashMap::new();
fields.insert("agent".to_string(), Value::String("dev".to_string()));
update_story_in_file(tmp.path(), "24_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "24_test").unwrap();
assert!(
result.contains("agent: \"dev\""),
"agent field should be set"
);
assert!(result.contains("name: T"), "name field preserved");
}
#[test]
fn update_story_sets_arbitrary_front_matter_fields() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"25_test",
"---\nname: T\n---\n\n## User Story\n\nSome story\n",
);
let mut fields = HashMap::new();
fields.insert("qa".to_string(), Value::String("human".to_string()));
fields.insert("priority".to_string(), Value::String("high".to_string()));
update_story_in_file(tmp.path(), "25_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "25_test").unwrap();
assert!(result.contains("qa: \"human\""), "qa field should be set");
assert!(
result.contains("priority: \"high\""),
"priority field should be set"
);
assert!(result.contains("name: T"), "name field preserved");
}
#[test]
fn update_story_front_matter_only_no_section_required() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"26_test",
"---\nname: T\n---\n\nNo sections here.\n",
);
let mut fields = HashMap::new();
fields.insert("agent".to_string(), Value::String("dev".to_string()));
let result = update_story_in_file(tmp.path(), "26_test", None, None, Some(&fields));
assert!(
result.is_ok(),
"front-matter-only update should not require body sections"
);
let contents = read_story_content(tmp.path(), "26_test").unwrap();
assert!(contents.contains("agent: \"dev\""));
}
#[test]
fn update_story_bool_front_matter_written_unquoted() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "27_test", "---\nname: T\n---\n\nNo sections.\n");
// String "false" still works (backwards compatibility).
let mut fields = HashMap::new();
fields.insert("blocked".to_string(), Value::String("false".to_string()));
update_story_in_file(tmp.path(), "27_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "27_test").unwrap();
assert!(
result.contains("blocked: false"),
"bool should be unquoted: {result}"
);
assert!(
!result.contains("blocked: \"false\""),
"bool must not be quoted: {result}"
);
}
#[test]
fn update_story_integer_front_matter_written_unquoted() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "28_test", "---\nname: T\n---\n\nNo sections.\n");
// String "0" still works (backwards compatibility).
let mut fields = HashMap::new();
fields.insert("retry_count".to_string(), Value::String("0".to_string()));
update_story_in_file(tmp.path(), "28_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "28_test").unwrap();
assert!(
result.contains("retry_count: 0"),
"integer should be unquoted: {result}"
);
assert!(
!result.contains("retry_count: \"0\""),
"integer must not be quoted: {result}"
);
}
#[test]
fn update_story_bool_front_matter_parseable_after_write() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"29_test",
"---\nname: My Story\n---\n\nNo sections.\n",
);
let mut fields = HashMap::new();
fields.insert("blocked".to_string(), Value::String("false".to_string()));
update_story_in_file(tmp.path(), "29_test", None, None, Some(&fields)).unwrap();
let contents = read_story_content(tmp.path(), "29_test").unwrap();
let meta = parse_front_matter(&contents).expect("front matter should parse");
assert_eq!(
meta.name.as_deref(),
Some("My Story"),
"name preserved after writing bool field"
);
}
// ── Bug 493 regression tests ──────────────────────────────────────────────
#[test]
fn update_story_depends_on_stored_as_yaml_array_not_quoted_string() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "30_test", "---\nname: T\n---\n\nNo sections.\n");
// String "[490]" still works (backwards compatibility).
let mut fields = HashMap::new();
fields.insert("depends_on".to_string(), Value::String("[490]".to_string()));
update_story_in_file(tmp.path(), "30_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "30_test").unwrap();
assert!(
result.contains("depends_on: [490]"),
"should be unquoted array: {result}"
);
assert!(
!result.contains("depends_on: \"[490]\""),
"must not be quoted: {result}"
);
let meta = parse_front_matter(&result).expect("front matter should parse");
assert_eq!(meta.depends_on, Some(vec![490]));
}
#[test]
fn update_story_native_bool_written_unquoted() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "31_test", "---\nname: T\n---\n\nNo sections.\n");
let mut fields = HashMap::new();
fields.insert("blocked".to_string(), Value::Bool(false));
update_story_in_file(tmp.path(), "31_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "31_test").unwrap();
assert!(
result.contains("blocked: false"),
"native bool false should be unquoted: {result}"
);
assert!(
!result.contains("blocked: \"false\""),
"must not be quoted: {result}"
);
}
#[test]
fn update_story_native_bool_true_written_unquoted() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "32_test", "---\nname: T\n---\n\nNo sections.\n");
let mut fields = HashMap::new();
fields.insert("blocked".to_string(), Value::Bool(true));
update_story_in_file(tmp.path(), "32_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "32_test").unwrap();
assert!(
result.contains("blocked: true"),
"native bool true should be unquoted: {result}"
);
assert!(
!result.contains("blocked: \"true\""),
"must not be quoted: {result}"
);
}
#[test]
fn update_story_native_integer_written_unquoted() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"33b_test",
"---\nname: T\n---\n\nNo sections.\n",
);
let mut fields = HashMap::new();
fields.insert("retry_count".to_string(), serde_json::json!(3));
update_story_in_file(tmp.path(), "33b_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "33b_test").unwrap();
assert!(
result.contains("retry_count: 3"),
"native integer should be unquoted: {result}"
);
assert!(
!result.contains("retry_count: \"3\""),
"must not be quoted: {result}"
);
}
#[test]
fn update_story_native_array_written_as_yaml_sequence() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "34_test", "---\nname: T\n---\n\nNo sections.\n");
let mut fields = HashMap::new();
fields.insert("depends_on".to_string(), serde_json::json!([490, 491]));
update_story_in_file(tmp.path(), "34_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "34_test").unwrap();
assert!(
result.contains("depends_on: [490, 491]"),
"native array should be YAML sequence: {result}"
);
assert!(
!result.contains("depends_on: \"["),
"must not be quoted: {result}"
);
let meta = parse_front_matter(&result).expect("front matter should parse");
assert_eq!(meta.depends_on, Some(vec![490, 491]));
}
#[test]
fn update_story_native_bool_parseable_after_write() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(
tmp.path(),
"35_test",
"---\nname: My Story\n---\n\nNo sections.\n",
);
let mut fields = HashMap::new();
fields.insert("blocked".to_string(), Value::Bool(false));
update_story_in_file(tmp.path(), "35_test", None, None, Some(&fields)).unwrap();
let contents = read_story_content(tmp.path(), "35_test").unwrap();
let meta = parse_front_matter(&contents).expect("front matter should parse");
assert_eq!(
meta.name.as_deref(),
Some("My Story"),
"name preserved after writing native bool"
);
}
#[test]
fn update_story_depends_on_multi_element_array() {
let tmp = tempfile::tempdir().unwrap();
setup_story_in_fs(tmp.path(), "31_test", "---\nname: T\n---\n\nNo sections.\n");
// String "[490, 491]" still works (backwards compatibility).
let mut fields = HashMap::new();
fields.insert(
"depends_on".to_string(),
Value::String("[490, 491]".to_string()),
);
update_story_in_file(tmp.path(), "31_test", None, None, Some(&fields)).unwrap();
let result = read_story_content(tmp.path(), "31_test").unwrap();
let meta = parse_front_matter(&result).expect("front matter should parse");
assert_eq!(meta.depends_on, Some(vec![490, 491]));
}
}
+6 -63
View File
@@ -1,5 +1,4 @@
//! Test result persistence — writes structured test results into story markdown files.
use crate::db::yaml_legacy::set_front_matter_field;
use crate::workflow::{StoryTestResults, TestCaseResult, TestStatus};
use std::path::Path;
@@ -27,7 +26,7 @@ pub fn write_test_results_to_story_file(
// Write back to content store and CRDT.
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &new_contents);
write_story_content(project_root, story_id, &stage, &new_contents, None);
Ok(())
}
@@ -43,31 +42,6 @@ pub fn read_test_results_from_story_file(
parse_test_results_from_contents(&contents)
}
/// Write coverage baseline to the front matter of a story.
///
/// If the story is not found, this is a no-op (returns Ok).
pub fn write_coverage_baseline_to_story_file(
project_root: &Path,
story_id: &str,
coverage_pct: f64,
) -> Result<(), String> {
let contents = match read_story_content(project_root, story_id) {
Ok(c) => c,
Err(_) => return Ok(()), // No story — skip silently
};
let updated = set_front_matter_field(
&contents,
"coverage_baseline",
&format!("{coverage_pct:.1}%"),
);
let stage = story_stage(story_id).unwrap_or_else(|| "2_current".to_string());
write_story_content(project_root, story_id, &stage, &updated);
Ok(())
}
/// Build the `## Test Results` section text including JSON comment and human-readable summary.
fn build_test_results_section(json: &str, results: &StoryTestResults) -> String {
let mut s = String::from("## Test Results\n\n");
@@ -176,7 +150,7 @@ mod tests {
"8001_story_test",
"2_current",
"---\nname: Test\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Test\n---\n# Story\n"),
crate::db::ItemMeta::named("Test"),
);
let results = make_results();
@@ -202,9 +176,7 @@ mod tests {
"8002_story_check",
"2_current",
"---\nname: Check\n---\n# Story\n\n## Acceptance Criteria\n\n- [ ] AC1\n",
crate::db::ItemMeta::from_yaml(
"---\nname: Check\n---\n# Story\n\n## Acceptance Criteria\n\n- [ ] AC1\n",
),
crate::db::ItemMeta::named("Check"),
);
let results = make_results();
@@ -227,9 +199,7 @@ mod tests {
"8003_story_overwrite",
"2_current",
"---\nname: Overwrite\n---\n# Story\n\n## Test Results\n\n<!-- huskies-test-results: {} -->\n\n### Unit Tests (0 passed, 0 failed)\n\n*No unit tests recorded.*\n",
crate::db::ItemMeta::from_yaml(
"---\nname: Overwrite\n---\n# Story\n\n## Test Results\n\n<!-- huskies-test-results: {} -->\n\n### Unit Tests (0 passed, 0 failed)\n\n*No unit tests recorded.*\n",
),
crate::db::ItemMeta::named("Overwrite"),
);
let results = make_results();
@@ -249,7 +219,7 @@ mod tests {
"8004_story_empty",
"2_current",
"---\nname: Empty\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Empty\n---\n# Story\n"),
crate::db::ItemMeta::named("Empty"),
);
let result = read_test_results_from_story_file(tmp.path(), "8004_story_empty");
@@ -271,7 +241,7 @@ mod tests {
"8005_story_qa",
"3_qa",
"---\nname: QA Story\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: QA Story\n---\n# Story\n"),
crate::db::ItemMeta::named("QA Story"),
);
let results = StoryTestResults {
@@ -287,31 +257,4 @@ mod tests {
let read_back = read_test_results_from_story_file(tmp.path(), "8005_story_qa").unwrap();
assert_eq!(read_back.unit.len(), 1);
}
#[test]
fn write_coverage_baseline_to_story_file_updates_front_matter() {
let tmp = tempfile::tempdir().unwrap();
crate::db::ensure_content_store();
crate::db::write_item_with_content(
"8006_story_cov",
"2_current",
"---\nname: Cov Story\n---\n# Story\n",
crate::db::ItemMeta::from_yaml("---\nname: Cov Story\n---\n# Story\n"),
);
write_coverage_baseline_to_story_file(tmp.path(), "8006_story_cov", 75.4).unwrap();
let contents = read_story_content(tmp.path(), "8006_story_cov").unwrap();
assert!(
contents.contains("coverage_baseline: 75.4%"),
"got: {contents}"
);
}
#[test]
fn write_coverage_baseline_to_story_file_silent_on_missing_story() {
let tmp = tempfile::tempdir().unwrap();
let result = write_coverage_baseline_to_story_file(tmp.path(), "99_story_missing", 50.0);
assert!(result.is_ok());
}
}
+12 -8
View File
@@ -11,19 +11,23 @@ pub(crate) fn read_story_content(_project_root: &Path, story_id: &str) -> Result
}
/// Write story content to the DB content store and CRDT.
///
/// Pass `Some(name)` when creating a new item or renaming an existing one,
/// `None` to leave the existing name register untouched. The CRDT is the
/// single source of truth for every metadata field — callers must use the
/// typed setters (`crdt_state::set_depends_on`, `set_item_type`, …) for
/// anything beyond name.
pub(crate) fn write_story_content(
_project_root: &Path,
story_id: &str,
stage: &str,
content: &str,
name: Option<&str>,
) {
let mut meta = crate::db::ItemMeta::from_yaml(content);
// CRDT is the single source of truth for depends_on. Never overwrite the
// register from YAML here — the typed setter (crdt_state::set_depends_on)
// is the only authorised write path. Passing None leaves the existing
// register untouched on update and initialises new items to "" so the
// explicit set_depends_on call in each create function takes effect.
meta.depends_on = None;
let meta = crate::db::ItemMeta {
name: name.map(str::to_string),
..Default::default()
};
crate::db::write_item_with_content(story_id, stage, content, meta);
}
@@ -273,7 +277,7 @@ mod tests {
"9877_story_foo",
"1_backlog",
"---\nname: Foo\n---\n",
crate::db::ItemMeta::from_yaml("---\nname: Foo\n---\n"),
crate::db::ItemMeta::named("Foo"),
);
let tmp = tempfile::tempdir().unwrap();
assert!(next_item_number(tmp.path()).unwrap() >= 9878);