diff --git a/src/interop/tests.rs b/src/interop/tests.rs index 33974b0..dae699d 100644 --- a/src/interop/tests.rs +++ b/src/interop/tests.rs @@ -12,7 +12,7 @@ fn conversion_report_output_is_frozen() { }; let json = format!("{}\n", render_report_json(&report).unwrap()); assert_report_fixture(&json, "tests/fixtures/output/conversion-report.json"); - let sheet = crate::sheet::Sheet::detect(); + let sheet = crate::sheet::Sheet::plain(); assert_report_fixture( &render_report(&report, &sheet), "tests/fixtures/output/conversion-report.txt", diff --git a/src/sheet.rs b/src/sheet.rs index 42162ae..de6eb00 100644 --- a/src/sheet.rs +++ b/src/sheet.rs @@ -46,6 +46,13 @@ pub struct Sheet { } impl Sheet { + #[cfg(test)] + pub(crate) const fn plain() -> Self { + Self { + depth: Depth::Plain, + } + } + pub fn detect() -> Self { let colored = !NO_COLOR.load(Ordering::Relaxed) && std::env::var_os("NO_COLOR").is_none() @@ -107,3 +114,23 @@ impl Sheet { fn truecolor_terminal() -> bool { std::env::var("COLORTERM").is_ok_and(|value| value == "truecolor" || value == "24bit") } + +#[cfg(test)] +mod tests { + use super::Sheet; + + #[test] + fn plain_styles_preserve_text() { + let sheet = Sheet::plain(); + for rendered in [ + sheet.bold("text"), + sheet.dim("text"), + sheet.green("text"), + sheet.yellow("text"), + sheet.magenta("text"), + ] { + assert_eq!(rendered, "text"); + } + assert_eq!(sheet.ok("done"), " ✓ done"); + } +} diff --git a/src/spec/apply.rs b/src/spec/apply.rs index 6c851e7..fcdd364 100644 --- a/src/spec/apply.rs +++ b/src/spec/apply.rs @@ -33,10 +33,12 @@ pub(super) fn apply_delta( summary: MergeSummary::default(), warnings: Vec::new(), }; - apply_renamed(canonical, operations, capability, &mut result)?; - apply_removed(canonical, operations, capability, &mut result)?; - apply_modified(canonical, operations, capability, &mut result)?; - apply_added(canonical, operations, capability, &mut result)?; + let mut staged = canonical.clone(); + apply_renamed(&mut staged, operations, capability, &mut result)?; + apply_removed(&mut staged, operations, capability, &mut result)?; + apply_modified(&mut staged, operations, capability, &mut result)?; + apply_added(&mut staged, operations, capability, &mut result)?; + *canonical = staged; Ok(result) } @@ -50,7 +52,7 @@ fn apply_renamed( let DeltaOperation::Renamed { from, to, line } = operation else { continue; }; - let Some(source_index) = canonical.requirement_index(from) else { + let Some(source_index) = canonical.requirement_index(from, *line)? else { return Err(ParseIssue { line: Some(*line), message: format!( @@ -58,7 +60,9 @@ fn apply_renamed( ), }); }; - if canonical.requirement_index(to).is_some() { + if let Some(target_index) = canonical.requirement_index(to, *line)? + && target_index != source_index + { return Err(ParseIssue { line: Some(*line), message: format!( @@ -98,7 +102,7 @@ fn apply_removed( return Ok(()); } for (name, line) in removals { - let Some(element_index) = canonical.requirement_index(name) else { + let Some(element_index) = canonical.requirement_index(name, line)? else { return Err(ParseIssue { line: Some(line), message: format!( @@ -122,7 +126,9 @@ fn apply_modified( let DeltaOperation::Modified(requirement) = operation else { continue; }; - let Some(element_index) = canonical.requirement_index(&requirement.name) else { + let Some(element_index) = + canonical.requirement_index(&requirement.name, requirement.line)? + else { return Err(ParseIssue { line: Some(requirement.line), message: format!( @@ -168,7 +174,9 @@ fn apply_added( let DeltaOperation::Added(requirement) = operation else { continue; }; - if let Some(element_index) = canonical.requirement_index(&requirement.name) { + if let Some(element_index) = + canonical.requirement_index(&requirement.name, requirement.line)? + { if canonical.requirement_matches(element_index, requirement) { continue; } diff --git a/src/spec/apply/tests.rs b/src/spec/apply/tests.rs index b914fcd..4760f3c 100644 --- a/src/spec/apply/tests.rs +++ b/src/spec/apply/tests.rs @@ -1,5 +1,12 @@ use super::*; use crate::spec::model::Requirement; +use crate::spec::parse::{parse_canonical, parse_delta}; + +fn requirement_text(name: &str, action: &str) -> String { + format!( + "### Requirement: {name}\n\nThe tool SHALL {action}.\n\n#### Scenario: Review\n\n- WHEN a review completes\n- THEN the tool records the result\n" + ) +} fn requirement(name: &str, scenarios: &[&str]) -> Requirement { Requirement { @@ -10,6 +17,190 @@ fn requirement(name: &str, scenarios: &[&str]) -> Requirement { } } +#[test] +fn added_requirement_with_case_variant_name_is_rejected() { + let original = format!( + "## Requirements\n\n{}", + requirement_text("Temporary review state", "record the result") + ); + let mut canonical = parse_canonical(&original).unwrap(); + let operations = parse_delta(&format!( + "## ADDED Requirements\n\n{}", + requirement_text("Temporary Review State", "discard the result") + )) + .unwrap(); + + let issue = apply_delta(&mut canonical, &operations, "Cap") + .err() + .unwrap(); + + assert!(issue.message.contains("cannot add existing requirement")); + assert_eq!(canonical.requirement_count(), 1); + assert_eq!(canonical.render(), original); +} + +#[test] +fn added_requirement_identical_up_to_case_is_skipped() { + for line_ending in ["\n", "\r\n"] { + let original = format!( + "## Requirements\n\n{}", + requirement_text("Temporary review state", "record the result") + ) + .replace('\n', line_ending); + let mut canonical = parse_canonical(&original).unwrap(); + let operations = parse_delta(&format!( + "## ADDED Requirements\n\n{}", + requirement_text("Temporary Review State", "record the result") + )) + .unwrap(); + + let result = apply_delta(&mut canonical, &operations, "Cap").unwrap(); + + assert_eq!(result.summary.added, 0); + assert_eq!(canonical.requirement_count(), 1); + assert_eq!(canonical.render(), original); + assert!(!canonical.changed()); + } +} + +#[test] +fn ambiguous_legacy_names_reject_each_operation_without_mutation() { + let original = format!( + "## Requirements\n\n{}\n{}", + requirement_text("Temporary review state", "record the first result"), + requirement_text("Temporary Review State", "record the second result") + ); + let deltas = [ + "## REMOVED Requirements\n\n### Requirement: Temporary Review State\n".to_string(), + format!( + "## MODIFIED Requirements\n\n{}", + requirement_text("Temporary Review State", "record a changed result") + ), + "## RENAMED Requirements\n\n- FROM: `### Requirement: Temporary Review State`\n- TO: `### Requirement: New name`\n".to_string(), + format!( + "## ADDED Requirements\n\n{}", + requirement_text("Temporary Review State", "record the second result") + ), + ]; + for delta in deltas { + let mut canonical = parse_canonical(&original).unwrap(); + let operations = parse_delta(&delta).unwrap(); + + let issue = apply_delta(&mut canonical, &operations, "Cap") + .err() + .unwrap(); + + assert!(issue.message.contains("ambiguous requirement identity")); + assert_eq!(canonical.render(), original); + assert!(!canonical.changed()); + } +} + +#[test] +fn later_ambiguous_addition_preserves_canonical_after_removal() { + for line_ending in ["\n", "\r\n"] { + let original = format!( + "## Requirements\n\n{}\n{}\n{}", + requirement_text("Removable", "record the old result"), + requirement_text("Temporary review state", "record the first result"), + requirement_text("Temporary Review State", "record the second result"), + ) + .replace('\n', line_ending); + let mut canonical = parse_canonical(&original).unwrap(); + let before = canonical.clone(); + let operations = parse_delta(&format!( + "## REMOVED Requirements\n\n### Requirement: Removable\n\n## ADDED Requirements\n\n{}", + requirement_text("Temporary Review State", "record another result"), + )) + .unwrap(); + + let issue = apply_delta(&mut canonical, &operations, "Cap") + .err() + .unwrap(); + + assert!(issue.message.contains("ambiguous requirement identity")); + assert_eq!(canonical, before); + assert_eq!(canonical.render(), original); + } +} + +#[test] +fn later_errors_preserve_canonical_after_each_operation_kind() { + let original = format!( + "## Requirements\n\n{}\n{}\n{}", + requirement_text("Stable", "record the old result"), + requirement_text("Temporary review state", "record the first result"), + requirement_text("Temporary Review State", "record the second result"), + ); + let deltas = [ + "## RENAMED Requirements\n\n- FROM: `### Requirement: Stable`\n- TO: `### Requirement: Renamed`\n- FROM: `### Requirement: Missing`\n- TO: `### Requirement: Other`\n".to_string(), + "## REMOVED Requirements\n\n### Requirement: Stable\n\n### Requirement: Missing\n".to_string(), + format!( + "## MODIFIED Requirements\n\n{}\n{}", + requirement_text("Stable", "record a changed result"), + requirement_text("Missing", "record another result"), + ), + format!( + "## ADDED Requirements\n\n{}\n{}", + requirement_text("New requirement", "record a new result"), + requirement_text("Temporary Review State", "record another result"), + ), + ]; + for delta in deltas { + let mut canonical = parse_canonical(&original).unwrap(); + let before = canonical.clone(); + let operations = parse_delta(&delta).unwrap(); + + assert!(apply_delta(&mut canonical, &operations, "Cap").is_err()); + assert_eq!(canonical, before); + } +} + +#[test] +fn failed_delta_preserves_changes_from_an_earlier_successful_delta() { + let original = format!( + "## Requirements\n\n{}", + requirement_text("Stable", "record the old result"), + ); + let mut canonical = parse_canonical(&original).unwrap(); + let initial = parse_delta(&format!( + "## ADDED Requirements\n\n{}", + requirement_text("Previously added", "record the earlier result"), + )) + .unwrap(); + apply_delta(&mut canonical, &initial, "Cap").unwrap(); + let before = canonical.clone(); + assert!(before.changed()); + let failing = parse_delta( + "## REMOVED Requirements\n\n### Requirement: Stable\n\n### Requirement: Missing\n", + ) + .unwrap(); + + assert!(apply_delta(&mut canonical, &failing, "Cap").is_err()); + assert_eq!(canonical, before); +} + +#[test] +fn case_only_rename_updates_the_parsed_heading() { + let original = format!( + "## Requirements\n\n{}", + requirement_text("Temporary review state", "record the result") + ); + let mut canonical = parse_canonical(&original).unwrap(); + let operations = parse_delta( + "## RENAMED Requirements\n\n- FROM: `### Requirement: Temporary review state`\n- TO: `### Requirement: Temporary Review State`\n", + ) + .unwrap(); + + let result = apply_delta(&mut canonical, &operations, "Cap").unwrap(); + + assert_eq!(result.summary.renamed, 1); + assert_eq!( + canonical.render(), + original.replace("Temporary review state", "Temporary Review State") + ); +} + #[test] fn scenario_preservation_compares_occurrence_multiplicity() { let current = requirement("Repeated", &["Retry", "Retry"]); diff --git a/src/spec/model.rs b/src/spec/model.rs index 45ac4c1..4e38ae8 100644 --- a/src/spec/model.rs +++ b/src/spec/model.rs @@ -118,10 +118,31 @@ impl CanonicalSpec { } } - pub(super) fn requirement_index(&self, name: &str) -> Option { - self.body.iter().position(|element| { - matches!(element, BodyElement::Requirement(requirement) if requirement.name == name) - }) + pub(super) fn requirement_index( + &self, + name: &str, + line: usize, + ) -> Result, ParseIssue> { + let identity = requirement_identity(name); + let mut found = None; + for (index, element) in self.body.iter().enumerate() { + let BodyElement::Requirement(requirement) = element else { + continue; + }; + if requirement_identity(&requirement.name) != identity { + continue; + } + if found.is_some() { + return Err(ParseIssue { + line: Some(line), + message: format!( + "ambiguous requirement identity '{name}' matches multiple requirements" + ), + }); + } + found = Some(index); + } + Ok(found) } pub(super) fn is_new_capability(&self) -> bool { @@ -134,9 +155,12 @@ impl CanonicalSpec { requirement: &Requirement, ) -> bool { self.requirement(element_index).is_some_and(|existing| { - existing.name == requirement.name - && existing.content - == normalize_line_endings(&requirement.content, &self.line_ending) + requirement_identity(&existing.name) == requirement_identity(&requirement.name) + && requirement_body(&existing.content) + == requirement_body(&normalize_line_endings( + &requirement.content, + &self.line_ending, + )) }) } @@ -254,6 +278,22 @@ pub(super) struct ParseIssue { pub(super) message: String, } +/// Requirement identity for lookups: case- and whitespace-insensitive, +/// so a Title Case delta finds its sentence-case canonical twin instead +/// of appending a duplicate. Equality checks that decide whether an +/// edit applies keep exact comparison, so a case-only rename still +/// lands. +fn requirement_identity(name: &str) -> String { + name.split_whitespace() + .collect::>() + .join(" ") + .to_ascii_lowercase() +} + +fn requirement_body(content: &str) -> &str { + content.split_once('\n').map_or("", |(_, body)| body) +} + fn normalize_line_endings(content: &str, line_ending: &str) -> String { content .replace("\r\n", "\n") diff --git a/src/spec/tests.rs b/src/spec/tests.rs index a787a25..07faa99 100644 --- a/src/spec/tests.rs +++ b/src/spec/tests.rs @@ -1152,7 +1152,7 @@ mod output_fixtures { }), "tests/fixtures/output/change-list.json", ); - let sheet = crate::sheet::Sheet::detect(); + let sheet = crate::sheet::Sheet::plain(); assert_matches_fixture( &render_change_list(&summaries, &sheet), "tests/fixtures/output/change-list.txt", diff --git a/src/spec/transaction/mod.rs b/src/spec/transaction/mod.rs index 51c7a78..7557b94 100644 --- a/src/spec/transaction/mod.rs +++ b/src/spec/transaction/mod.rs @@ -156,11 +156,28 @@ pub(crate) struct Transaction { root: PathBuf, state_directory: PathBuf, journal_path: PathBuf, - _lock: File, + _lock: LockGuard, io: I, recovery: Option, } +struct LockGuard(File); + +impl LockGuard { + fn acquire(file: File) -> Result { + file.try_lock()?; + Ok(Self(file)) + } +} + +impl Drop for LockGuard { + fn drop(&mut self) { + // A fork can retain another descriptor until exec. + // Release the shared lock when this guard leaves scope. + let _ = self.0.unlock(); + } +} + /// The failure-injection seam, and the deliberate exception to RUST-0008 /// (no traits for internal types): recovery is testable only if every /// phase can fail on demand. Production holds [`SystemIo`] alone; the @@ -230,7 +247,7 @@ impl Transaction { .truncate(false) .open(&lock_path) .map_err(|error| io_error("open", &lock_path, error))?; - lock.try_lock().map_err(|error| { + let lock = LockGuard::acquire(lock).map_err(|error| { let message = match error { fs::TryLockError::WouldBlock => format!( "another spec archive transaction holds {}; retry after it finishes", @@ -614,18 +631,17 @@ pub(super) fn health_findings( Err(error) if error.kind() == io::ErrorKind::NotFound => None, Err(error) => return Err(io_error("open", &lock_path, error)), }; - if let Some(lock) = &lock - && let Err(error) = lock.try_lock() - { - return match error { - fs::TryLockError::WouldBlock => Ok(vec![TransactionHealthFinding { + let lock = match lock.map(LockGuard::acquire).transpose() { + Ok(lock) => lock, + Err(fs::TryLockError::WouldBlock) => { + return Ok(vec![TransactionHealthFinding { severity: super::DiagnosticSeverity::Warning, path: LOCK_FILE.to_string(), message: "another process holds the spec archive lock".to_string(), - }]), - fs::TryLockError::Error(error) => Err(io_error("lock", &lock_path, error)), - }; - } + }]); + } + Err(fs::TryLockError::Error(error)) => return Err(io_error("lock", &lock_path, error)), + }; let state_directory = root.join(TRANSACTION_DIRECTORY); if !state_directory.exists() { @@ -655,7 +671,7 @@ fn incomplete_transaction_findings( root: PathBuf, state_directory: PathBuf, journal_path: PathBuf, - lock: File, + lock: LockGuard, ) -> Result, Error> { let content = fs::read_to_string(&journal_path) .map_err(|error| io_error("read", &journal_path, error))?; diff --git a/src/spec/transaction/tests.rs b/src/spec/transaction/tests.rs index 473ae74..e7afa36 100644 --- a/src/spec/transaction/tests.rs +++ b/src/spec/transaction/tests.rs @@ -302,6 +302,62 @@ fn prepared_recovery_discards_staged_state() { assert_rolled_back(&fixture); } +#[test] +fn transaction_drop_releases_lock_with_a_duplicated_descriptor() { + let fixture = transaction_fixture(); + let transaction = acquire(&fixture.spec_root).unwrap(); + let Transaction { _lock: lock, .. } = &transaction; + let inherited_descriptor = lock.0.try_clone().unwrap(); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + + drop(transaction); + + let recovered = acquire(&fixture.spec_root).unwrap(); + drop(inherited_descriptor); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + drop(recovered); +} + +#[test] +fn incomplete_health_releases_lock_on_error_before_transaction() { + let fixture = transaction_fixture(); + let file = File::create(fixture.spec_root.base().join(LOCK_FILE)).unwrap(); + let inherited_descriptor = file.try_clone().unwrap(); + let lock = LockGuard::acquire(file).unwrap(); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + let state_directory = fixture.spec_root.base().join(TRANSACTION_DIRECTORY); + + let result = incomplete_transaction_findings( + &fixture.spec_root, + fixture.spec_root.base().to_path_buf(), + state_directory.clone(), + state_directory.join(JOURNAL_FILE), + lock, + ); + + assert!(result.is_err()); + let recovered = acquire(&fixture.spec_root).unwrap(); + drop(inherited_descriptor); + assert!( + acquire_error(&fixture) + .message() + .contains("another spec archive transaction") + ); + drop(recovered); +} + #[test] fn committing_recovery_restores_originals() { let fixture = fail_at_phase(Phase::Committing);