From f81957d0919c0c6ecb5820b3d1142f0186d6ec04 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 00:03:00 +0800 Subject: [PATCH 1/3] fix(report): retain Baseline coverage for regrouped clones Record hashed clone line occurrences so deleting a copy cannot expose surviving duplicates to the Budget. Count each uncovered line once, and reject Baseline edits that grant new coverage. Closes #765 --- crates/cli/src/commit_measurement.rs | 2 +- .../fixtures/duplication-baseline/long.txt | 20 +++ .../duplication-baseline/replacement.txt | 17 +++ .../fixtures/duplication-baseline/short.txt | 18 +++ crates/cli/tests/integration/baseline.rs | 108 +++++++++++++++- crates/cli/tests/integration/diff.rs | 5 +- crates/config/HOW-TO.md | 2 + crates/config/src/baseline.rs | 87 ++++++++++++- crates/config/src/baseline/tests.rs | 1 + crates/config/src/finding_anchor.rs | 45 ++++++- crates/config/src/finding_anchor/tests.rs | 1 + crates/config/src/lib.rs | 2 +- crates/config/src/state_check.rs | 17 ++- crates/report/HOW-TO.md | 2 + crates/report/src/baseline.rs | 119 +++++++++++++----- crates/report/src/clone_line_anchors.rs | 69 ++++++++++ crates/report/src/findings.rs | 1 + crates/report/src/lib.rs | 1 + crates/report/src/measurement.rs | 4 +- crates/report/src/render.rs | 12 +- crates/report/src/summary.rs | 14 ++- .../guide/adopting-on-an-existing-codebase.md | 1 + docs/reference.md | 5 + docs/verification/features/baseline.md | 7 ++ 24 files changed, 512 insertions(+), 48 deletions(-) create mode 100644 crates/cli/tests/fixtures/duplication-baseline/long.txt create mode 100644 crates/cli/tests/fixtures/duplication-baseline/replacement.txt create mode 100644 crates/cli/tests/fixtures/duplication-baseline/short.txt create mode 100644 crates/report/src/clone_line_anchors.rs diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 81d98fbc..2add79bb 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -17,7 +17,7 @@ use crate::check::{ use crate::describe; const CODEINT_VERSION: &str = env!("CARGO_PKG_VERSION"); -const MEASUREMENT_CACHE_VERSION: u32 = 10; +const MEASUREMENT_CACHE_VERSION: u32 = 11; #[derive(Serialize)] struct MeasurementSettings<'configuration> { diff --git a/crates/cli/tests/fixtures/duplication-baseline/long.txt b/crates/cli/tests/fixtures/duplication-baseline/long.txt new file mode 100644 index 00000000..b08ddc49 --- /dev/null +++ b/crates/cli/tests/fixtures/duplication-baseline/long.txt @@ -0,0 +1,20 @@ +export function first(item: Record) { + let total = 0; + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + for (const n of [item.x, item.y, item.z]) total += n; + total += Math.sign(item.x) * (item.y - item.z); + total *= item.x > 0 ? item.y : item.z; + for (const n of [item.x, item.y, item.z]) total += n; + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + total += Math.sign(item.x) * (item.y - item.z); + for (const n of [item.x, item.y, item.z]) total += n; + total *= item.x > 0 ? item.y : item.z; + switch (item.x) { case 3: total += item.y; break; default: total -= item.z; } + total *= item.x > 0 ? item.y : item.z; + total += Math.sign(item.x) * (item.y - item.z); + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + total *= item.x > 0 ? item.y : item.z; + total += Math.sign(item.x) * (item.y - item.z); + return total; +} diff --git a/crates/cli/tests/fixtures/duplication-baseline/replacement.txt b/crates/cli/tests/fixtures/duplication-baseline/replacement.txt new file mode 100644 index 00000000..ca68ecb1 --- /dev/null +++ b/crates/cli/tests/fixtures/duplication-baseline/replacement.txt @@ -0,0 +1,17 @@ +export const third = { + currency: 'USD', + region: 'north', + notes: ['manual', 'reviewed'], + offset: null, + retries: 2, + enabled: true, + aliases: new Set(['short', 'long']), + limit: 300, + window: { starts: 12, ends: 42 }, + owner: { active: false }, + account: { kind: 'sample' }, + count: 91, + empty: [], + route: '/test', + threshold: 0.25, +}; diff --git a/crates/cli/tests/fixtures/duplication-baseline/short.txt b/crates/cli/tests/fixtures/duplication-baseline/short.txt new file mode 100644 index 00000000..989a8e9b --- /dev/null +++ b/crates/cli/tests/fixtures/duplication-baseline/short.txt @@ -0,0 +1,18 @@ +export function third(item: Record) { + let total = 0; + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + for (const n of [item.x, item.y, item.z]) total += n; + total += Math.sign(item.x) * (item.y - item.z); + total *= item.x > 0 ? item.y : item.z; + for (const n of [item.x, item.y, item.z]) total += n; + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + total += Math.sign(item.x) * (item.y - item.z); + for (const n of [item.x, item.y, item.z]) total += n; + total *= item.x > 0 ? item.y : item.z; + switch (item.x) { case 3: total += item.y; break; default: total -= item.z; } + total *= item.x > 0 ? item.y : item.z; + total += Math.sign(item.x) * (item.y - item.z); + if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; } + return total; +} diff --git a/crates/cli/tests/integration/baseline.rs b/crates/cli/tests/integration/baseline.rs index 3df108f5..d2b042fa 100644 --- a/crates/cli/tests/integration/baseline.rs +++ b/crates/cli/tests/integration/baseline.rs @@ -3,7 +3,9 @@ use std::path::Path; use serde_json::{Value, json}; -use crate::common::{eroded_ts, finding_lines, init_git_repo, run_codeint_text, write_repo_files}; +use crate::common::{ + eroded_ts, finding_lines, init_git_repo, run_codeint_text, run_git, write_repo_files, +}; const BASELINE_FILE: &str = ".codeint/baseline.json"; const STRICT_EROSION_BUDGET: &str = r#"{ "budgets": { "production": { "erosion": 0 } } }"#; @@ -48,6 +50,110 @@ fn legacy_repository() -> tempfile::TempDir { ]) } +fn duplication_repository() -> tempfile::TempDir { + let first = include_str!("../fixtures/duplication-baseline/long.txt"); + let short = include_str!("../fixtures/duplication-baseline/short.txt"); + init_git_repo(&[ + ( + "codeint.yaml", + concat!( + "budgets:\n production:\n duplication: 0\n", + "duplication:\n near_clones: false\n", + "regression_limits:\n cognitive_complexity:\n ratio_rise: 1\n", + ), + ), + ("a.ts", first), + ("b.ts", &first.replace("function first", "function second")), + ("c.ts", short), + ]) +} + +#[test] +fn duplication_baseline_covers_surviving_overlapping_clone_spans() { + let repo = duplication_repository(); + let before = check_json(repo.path(), &["--all"], 1); + let before = &before["source_sets"]["production"]["duplication"]; + assert_eq!(before["clone_lines"], 56); + assert_eq!(before["clone_groups"].as_array().map(Vec::len), Some(2)); + run_codeint_text(repo.path(), &["baseline", "update"], 0); + check_json(repo.path(), &["--all"], 0); + run_git(repo.path(), &["add", BASELINE_FILE]); + run_git(repo.path(), &["commit", "-qm", "record Baseline"]); + + let replacement = include_str!("../fixtures/duplication-baseline/replacement.txt"); + write_repo_files(repo.path(), &[("c.ts", replacement)]); + let after = check_json(repo.path(), &["--all"], 0); + assert_eq!( + after["source_sets"]["production"]["duplication"]["clone_lines"], + 40 + ); + assert_eq!( + after["source_sets"]["production"]["duplication"]["clone_groups"], + json!([]) + ); + run_codeint_text(repo.path(), &["diff", "HEAD", "--format", "json"], 0); + run_codeint_text(repo.path(), &["baseline", "update"], 0); + run_codeint_text(repo.path(), &["state", "check", "HEAD"], 0); + check_json(repo.path(), &["--all"], 0); +} + +#[test] +fn duplication_baseline_does_not_cover_a_new_copy_of_a_baselined_clone() { + let repo = duplication_repository(); + run_codeint_text(repo.path(), &["baseline", "update"], 0); + check_json(repo.path(), &["--all"], 0); + + let first = include_str!("../fixtures/duplication-baseline/long.txt"); + write_repo_files( + repo.path(), + &[("new.ts", &first.replace("function first", "function fresh"))], + ); + let report = check_json(repo.path(), &["--all"], 1); + let groups = report["source_sets"]["production"]["duplication"]["clone_groups"] + .as_array() + .expect("clone groups"); + assert!(groups.iter().any(|group| { + group["locations"] + .as_array() + .expect("clone locations") + .iter() + .any(|location| location["path"] == "new.ts") + })); + let budgets = report["over_budget"].as_array().expect("Budget failures"); + assert!(budgets.iter().any(|budget| { + budget["metric"] == "duplication" + && budget["ratio"] == json!(0.2564) + && budget["non_baselined"] == true + })); +} + +#[test] +fn duplication_baseline_state_check_rejects_widened_clone_coverage() { + let repo = duplication_repository(); + run_codeint_text(repo.path(), &["baseline", "update"], 0); + run_git(repo.path(), &["add", BASELINE_FILE]); + run_git(repo.path(), &["commit", "-qm", "record Baseline"]); + let mut edited = baseline_file(repo.path()); + let finding = &mut edited["source_sets"]["production"]["duplication"]["findings"][0]; + let lines = finding["clone_lines"] + .as_array_mut() + .expect("clone line anchors"); + let mut added = lines[0].clone(); + added["occurrence"] = json!(99); + lines.push(added); + fs::write(repo.path().join(BASELINE_FILE), edited.to_string()).expect("write wider Baseline"); + let (stdout, _) = run_codeint_text( + repo.path(), + &["state", "check", "HEAD", "--format", "json"], + 1, + ); + let report: Value = serde_json::from_str(&stdout).expect("state check report"); + let violation = &report["violations"][0]; + assert_eq!(violation["kind"], "baseline_findings_added"); + assert_eq!(violation["source_set"], "production"); + assert_eq!(violation["metric"], "duplication"); +} + #[test] fn check_hides_baselined_findings_and_evaluates_budgets_on_new_findings_only() { let repo = legacy_repository(); diff --git a/crates/cli/tests/integration/diff.rs b/crates/cli/tests/integration/diff.rs index 428dc8a9..72f3105d 100644 --- a/crates/cli/tests/integration/diff.rs +++ b/crates/cli/tests/integration/diff.rs @@ -1644,6 +1644,7 @@ fn a_result_cached_under_plugin_interface_0_2_0_or_cache_version_7_is_not_reused with_cache_version(¤t_settings, 7), with_cache_version(¤t_settings, 8), with_cache_version(¤t_settings, 9), + with_cache_version(¤t_settings, 10), ] { let (seeded_cache, report) = seed_cache_and_diff_json(&fixture, commit, &legacy_settings, &stale_result); @@ -1658,7 +1659,7 @@ fn a_result_cached_under_plugin_interface_0_2_0_or_cache_version_7_is_not_reused } assert_eq!(current_settings["plugin_interface_version"], json!("0.5.0")); - assert_eq!(current_settings["cache_version"], json!(10)); + assert_eq!(current_settings["cache_version"], json!(11)); } #[test] @@ -1682,7 +1683,7 @@ fn stale_cache_version_9_misses_and_re_measures_with_body_hashes_and_anchor_fiel .expect("settings string in cache entry"), ) .expect("parse settings"); - if settings["cache_version"] == json!(10) { + if settings["cache_version"] == json!(11) { fresh_entries.push(parsed["result"].clone()); } } diff --git a/crates/config/HOW-TO.md b/crates/config/HOW-TO.md index 2fc6bdd8..d0dd46cf 100644 --- a/crates/config/HOW-TO.md +++ b/crates/config/HOW-TO.md @@ -154,6 +154,8 @@ updated.write_atomic(repository.root())?; - `Baseline::match_findings(source_set, metric, candidates)` and `match_anchors(references, candidates)` match Findings by occurrence-free content hash and context anchors (exact `id` matching for id-only entries); pass `None` as the Source set for Dependency hygiene Metrics. - `remap_anchor_paths`, `match_anchors_with_renames`, `match_anchors_with_aliases`, `Baseline::match_findings_with_renames`, and `Baseline::match_findings_with_aliases` preserve both `schema_version` `1` and `schema_version` `2` Baseline matches across detected file renames (`old_path -> new_path`), matching opaque hashed anchors via `body` plus remapped `paths` and context-anchor disambiguation without parsing source files. - `Baseline::update` always writes `schema_version` `2`, records every Finding on the first run, later only removes fixed Findings (refreshing matched anchors and counting new ones in `skipped_new`), refreshes Metrics whose Metric version changed, replaces every measured Metric's Findings when `reset` is `true`, and keeps entries of unmeasured Metrics. +- `BaselineEntry::covered_clone_lines` returns stored Duplication occurrence anchors, with detected renames applied to the hashed paths. +- A regular Duplication Baseline update retains only clone line anchors that the current measurement still covers. ## Compare Ratchet and Baseline state files diff --git a/crates/config/src/baseline.rs b/crates/config/src/baseline.rs index 4a284b13..038136f1 100644 --- a/crates/config/src/baseline.rs +++ b/crates/config/src/baseline.rs @@ -6,7 +6,8 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::finding_anchor::{ - AnchorMatch, FindingAnchor, match_anchors, match_anchors_with_aliases, + AnchorMatch, CloneLineAnchor, FindingAnchor, clone_line_renames, match_anchors, + match_anchors_with_aliases, }; use crate::repo_state::{ DEPENDENCY_METRIC_KEYS, LoadedForUpdate, MetricVersionMismatch, RepoStateFile, @@ -29,6 +30,24 @@ pub struct BaselineEntry { pub findings: Vec, } +impl BaselineEntry { + pub fn covered_clone_lines( + &self, + renames: &BTreeMap, + ) -> BTreeSet { + let renames = clone_line_renames(renames); + self.findings + .iter() + .flat_map(|finding| { + finding + .clone_lines + .iter() + .map(|line| line.with_rename(&renames)) + }) + .collect() + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Baseline { @@ -339,6 +358,9 @@ fn next_entry( ) -> BaselineEntry { let stored: &[FindingAnchor] = previous.map_or(&[], |entry| entry.findings.as_slice()); let version_changed = previous.is_some_and(|entry| entry.metric_version != item.metric_version); + if item.metric == "duplication" && !accept_current && !version_changed { + return update_duplication(stored, item, summary); + } let matched = match_anchors(stored, &item.findings); let matched_count = matched.matched_pairs.len(); let unmatched_current = item.findings.len() - matched_count; @@ -362,3 +384,66 @@ fn next_entry( findings, } } + +fn update_duplication( + stored: &[FindingAnchor], + item: &MeasuredBaselineMetric, + summary: &mut BaselineUpdateSummary, +) -> BaselineEntry { + let current_lines: BTreeSet<_> = item + .findings + .iter() + .flat_map(|finding| finding.clone_lines.iter().copied()) + .collect(); + let legacy: Vec<_> = stored + .iter() + .filter(|finding| finding.clone_lines.is_empty()) + .cloned() + .collect(); + let matched = match_anchors(&legacy, &item.findings); + let mut findings: Vec<_> = matched + .matched_pairs + .iter() + .map(|&(_, current)| { + let mut finding = item.findings[current].clone(); + finding.clone_lines.clear(); + finding + }) + .collect(); + findings.extend( + stored + .iter() + .filter(|finding| !finding.clone_lines.is_empty()) + .filter_map(|finding| { + let mut finding = finding.clone(); + finding + .clone_lines + .retain(|line| current_lines.contains(line)); + (!finding.clone_lines.is_empty()).then_some(finding) + }), + ); + let covered: BTreeSet<_> = findings + .iter() + .flat_map(|finding| &finding.clone_lines) + .collect(); + let matched_current = matched.matched_candidates(item.findings.len()); + summary.skipped_new += item + .findings + .iter() + .zip(matched_current) + .filter(|(finding, legacy_match)| { + !legacy_match + && (finding.clone_lines.is_empty() + || finding + .clone_lines + .iter() + .any(|line| !covered.contains(line))) + }) + .count(); + summary.removed += stored.len().saturating_sub(findings.len()); + findings.sort(); + BaselineEntry { + metric_version: item.metric_version, + findings, + } +} diff --git a/crates/config/src/baseline/tests.rs b/crates/config/src/baseline/tests.rs index de4587d2..dbe210cb 100644 --- a/crates/config/src/baseline/tests.rs +++ b/crates/config/src/baseline/tests.rs @@ -148,6 +148,7 @@ fn parse_supports_schema_v1_and_v2_and_rejects_unknown_schema_and_zero_metric_ve before: Some("b1".to_owned()), after: None, line: Some(2), + clone_lines: Vec::new(), }] ); } diff --git a/crates/config/src/finding_anchor.rs b/crates/config/src/finding_anchor.rs index 2c92eeab..a4c2b206 100644 --- a/crates/config/src/finding_anchor.rs +++ b/crates/config/src/finding_anchor.rs @@ -28,6 +28,40 @@ pub struct FindingAnchor { pub after: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub clone_lines: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CloneLineAnchor { + path: u64, + occurrence: u32, + content: u64, +} + +impl CloneLineAnchor { + pub fn new(path: &str, occurrence: u32, content: u64) -> Self { + Self { + path: anchor_path_digest(path), + occurrence, + content, + } + } + + pub(crate) fn with_rename(self, renames: &HashMap) -> Self { + Self { + path: renames.get(&self.path).copied().unwrap_or(self.path), + ..self + } + } +} + +pub(crate) fn clone_line_renames(renames: &BTreeMap) -> HashMap { + renames + .iter() + .map(|(old, new)| (anchor_path_digest(old), anchor_path_digest(new))) + .collect() } impl FindingAnchor { @@ -40,6 +74,7 @@ impl FindingAnchor { before: None, after: None, line: None, + clone_lines: Vec::new(), } } @@ -58,6 +93,7 @@ impl FindingAnchor { before: before.map(|value| format!("{value:016x}")), after: after.map(|value| format!("{value:016x}")), line, + clone_lines: Vec::new(), } } @@ -77,12 +113,15 @@ impl FindingAnchor { } fn hash_anchor_path(path: &str) -> String { - let digest = StableHasher::new() + format!("{:016x}", anchor_path_digest(path)) +} + +fn anchor_path_digest(path: &str) -> u64 { + StableHasher::new() .write_bytes(b"codeint.anchor.path.v1") .write_u64(path.len() as u64) .write_bytes(path.as_bytes()) - .finish(); - format!("{digest:016x}") + .finish() } #[derive(Debug, Clone, Default, PartialEq, Eq)] diff --git a/crates/config/src/finding_anchor/tests.rs b/crates/config/src/finding_anchor/tests.rs index 04320276..c47a3052 100644 --- a/crates/config/src/finding_anchor/tests.rs +++ b/crates/config/src/finding_anchor/tests.rs @@ -15,6 +15,7 @@ fn anchor( before: before.map(str::to_owned), after: after.map(str::to_owned), line: Some(line), + clone_lines: Vec::new(), } } diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 74c99c64..c0190d73 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -78,7 +78,7 @@ pub use coupling::{ pub use dependencies::DependenciesConfig; pub use dialects::{DialectConflict, DialectRules, validate_dialects}; pub use finding_anchor::{ - AnchorMatch, FindingAnchor, match_anchors, match_anchors_with_aliases, + AnchorMatch, CloneLineAnchor, FindingAnchor, match_anchors, match_anchors_with_aliases, match_anchors_with_renames, remap_anchor_paths, }; pub use framework_profiles::{FrameworkProfilesConfig, display_package_key}; diff --git a/crates/config/src/state_check.rs b/crates/config/src/state_check.rs index c6136b22..510cbbff 100644 --- a/crates/config/src/state_check.rs +++ b/crates/config/src/state_check.rs @@ -273,12 +273,25 @@ fn compare_baseline_entry( return; } let matched = match_anchors_with_renames(&base_entry.findings, &head_entry.findings, renames); - let matched_head = matched.matched_candidates(head_entry.findings.len()); + let mut matched_head = vec![None; head_entry.findings.len()]; + for (base, head) in matched.matched_pairs { + matched_head[head] = Some(&base_entry.findings[base]); + } + let covered_clone_lines = base_entry.covered_clone_lines(renames); let mut added_ids: Vec = head_entry .findings .iter() .enumerate() - .filter(|&(index, _)| !matched_head[index]) + .filter(|&(index, finding)| { + if finding.clone_lines.is_empty() { + return matched_head[index].is_none_or(|old| !old.clone_lines.is_empty()); + } + matched_head[index].is_none() + || finding + .clone_lines + .iter() + .any(|line| !covered_clone_lines.contains(line)) + }) .map(|(_, finding)| finding.id.clone()) .collect(); if !added_ids.is_empty() { diff --git a/crates/report/HOW-TO.md b/crates/report/HOW-TO.md index 6e56f3b7..b050e82b 100644 --- a/crates/report/HOW-TO.md +++ b/crates/report/HOW-TO.md @@ -46,6 +46,8 @@ if !report.over_budget().is_empty() { - `ratchet_metrics` returns every measured Metric's rounded ratio and `metric_version` for Ratchet checking or updating. - Set `ReportOptions::baseline` to a loaded `codeint_config::Baseline` to leave out baselined Findings before ownership filtering and truncation; each Metric then records `baselined_findings`, the report records `baseline` (`path`, `hidden_findings`), and each Budget compares with the non-baselined ratio (measured ratio times the unhidden share of Finding weight), marking such failures `non_baselined`. - `baseline_metrics` returns each measured Metric's `metric_version` and `FindingAnchor` entries of its listed Findings; build the report with `FindingsShown::All`, no ownership filter, and no Baseline before passing them to `Baseline::update`. +- Duplication Findings carry anchors for hashed clone line occurrences. + The report hides a Clone group when all its lines are covered, and scales its Budget by the share of unique clone lines still uncovered. - `render_baseline_update(&summary, format)` prints the `codeint baseline update` summary as `text`, `toon`, or `json`. - `StateCheckReport::from_comparison(base, head, ratchet_path, baseline_path, comparison)` builds the `codeint state check` report (`STATE_CHECK_SCHEMA_VERSION == 1`), renders `toon`, `text`, or `json` via `render(StateCheckFormat)`, exposes `failure_messages()`, and validates against `ReportSchemaKind::StateCheck` (`schema/reports/state-check.schema.json`). diff --git a/crates/report/src/baseline.rs b/crates/report/src/baseline.rs index d32136ef..1ac2343d 100644 --- a/crates/report/src/baseline.rs +++ b/crates/report/src/baseline.rs @@ -1,6 +1,6 @@ use std::collections::{BTreeMap, HashSet}; -use codeint_config::{BASELINE_PATH, Baseline, FindingAnchor}; +use codeint_config::{BASELINE_PATH, Baseline, FindingAnchor, match_anchors_with_aliases}; use codeint_metrics::{FindingContext, FindingId}; use codeint_model::SourceSet; use serde::{Deserialize, Serialize}; @@ -72,13 +72,83 @@ pub(crate) struct BaselineScope<'a> { } impl BaselineScope<'_> { - fn hidden_mask(&self, metric: &str, rows: &[R]) -> Option<(Vec, usize)> { - let anchors: Vec = rows.iter().map(Identified::anchor).collect(); - let matched = self - .baseline - .match_findings(self.source_set, metric, &anchors); - let hidden_count = matched.matched_pairs.len(); - (hidden_count > 0).then(|| (matched.matched_candidates(rows.len()), hidden_count)) + fn coverage( + &self, + metric: &str, + rows: &[R], + aliases: &[Option], + renames: &BTreeMap, + ) -> Option<(Vec, f64)> { + let anchors: Vec<_> = rows.iter().map(Identified::anchor).collect(); + if metric == "duplication" + && let Some(coverage) = self.clone_coverage(&anchors, aliases, renames) + { + return Some(coverage); + } + let matched = self.baseline.match_findings_with_aliases( + self.source_set, + metric, + &anchors, + aliases, + renames, + ); + if matched.matched_pairs.is_empty() { + return None; + } + let is_hidden = matched.matched_candidates(rows.len()); + let retained_share = retained_share_from_mask(rows, &is_hidden); + Some((is_hidden, retained_share)) + } + + fn clone_coverage( + &self, + anchors: &[FindingAnchor], + aliases: &[Option], + renames: &BTreeMap, + ) -> Option<(Vec, f64)> { + let entry = self.baseline.entry(self.source_set, "duplication")?; + let mut covered = entry.covered_clone_lines(renames); + if covered.is_empty() { + return None; + } + let legacy: Vec<_> = entry + .findings + .iter() + .filter(|anchor| anchor.clone_lines.is_empty()) + .cloned() + .collect(); + let legacy_matched = match_anchors_with_aliases(&legacy, anchors, aliases, renames) + .matched_candidates(anchors.len()); + covered.extend( + anchors + .iter() + .zip(&legacy_matched) + .filter(|(_, matched)| **matched) + .flat_map(|(anchor, _)| anchor.clone_lines.iter().copied()), + ); + let measured: HashSet<_> = anchors + .iter() + .flat_map(|anchor| anchor.clone_lines.iter().copied()) + .collect(); + let uncovered = measured + .iter() + .filter(|line| !covered.contains(line)) + .count(); + let is_hidden: Vec<_> = anchors + .iter() + .zip(legacy_matched) + .map(|(anchor, legacy_match)| { + legacy_match + || (!anchor.clone_lines.is_empty() + && anchor.clone_lines.iter().all(|line| covered.contains(line))) + }) + .collect(); + let retained_share = if measured.is_empty() { + 1.0 + } else { + uncovered as f64 / measured.len() as f64 + }; + Some((is_hidden, retained_share)) } pub(crate) fn split( @@ -86,26 +156,22 @@ impl BaselineScope<'_> { metric: &str, rows: Vec, ) -> (Vec, Baselined, HashSet) { - let Some((is_hidden, hidden_count)) = self.hidden_mask(metric, &rows) else { + let Some((is_hidden, retained_share)) = self.coverage(metric, &rows, &[], &BTreeMap::new()) + else { return (rows, Baselined::default(), HashSet::new()); }; - let mut hidden = Vec::with_capacity(hidden_count); - let mut visible = Vec::with_capacity(rows.len() - hidden_count); + let hidden_count = is_hidden.iter().filter(|&&hide| hide).count(); + let mut visible = Vec::with_capacity(rows.len().saturating_sub(hidden_count)); let mut hidden_ids = HashSet::with_capacity(hidden_count); for (row, hide) in rows.into_iter().zip(is_hidden) { if hide { hidden_ids.insert(row.id().to_owned()); - hidden.push(row); } else { visible.push(row); } } - let retained_share = retained_weight_share( - &visible.iter().collect::>(), - &hidden.iter().collect::>(), - ); let baselined = Baselined { - hidden: hidden.len(), + hidden: hidden_count, retained_share: Some(retained_share), }; (visible, baselined, hidden_ids) @@ -116,8 +182,7 @@ impl BaselineScope<'_> { metric: &str, rows: &[R], ) -> Option { - let (is_hidden, _) = self.hidden_mask(metric, rows)?; - Some(retained_share_from_mask(rows, &is_hidden)) + self.retained_share_with_renames(metric, rows, &[], &BTreeMap::new()) } pub(crate) fn retained_share_with_renames( @@ -127,20 +192,8 @@ impl BaselineScope<'_> { aliases: &[Option], renames: &BTreeMap, ) -> Option { - let anchors: Vec = rows.iter().map(Identified::anchor).collect(); - let matched = self.baseline.match_findings_with_aliases( - self.source_set, - metric, - &anchors, - aliases, - renames, - ); - let hidden_count = matched.matched_pairs.len(); - if hidden_count == 0 { - return None; - } - let is_hidden = matched.matched_candidates(rows.len()); - Some(retained_share_from_mask(rows, &is_hidden)) + self.coverage(metric, rows, aliases, renames) + .map(|(_, share)| share) } } diff --git a/crates/report/src/clone_line_anchors.rs b/crates/report/src/clone_line_anchors.rs new file mode 100644 index 00000000..1278a5a3 --- /dev/null +++ b/crates/report/src/clone_line_anchors.rs @@ -0,0 +1,69 @@ +use std::collections::{BTreeMap, HashMap, HashSet}; + +use codeint_config::CloneLineAnchor; +use codeint_metrics::{CloneGroup, Duplication}; +use codeint_model::{RepoPath, SourceSetModel, StableHasher}; + +use crate::findings::CloneGroupFinding; + +pub(crate) struct CloneLineAnchors<'a>(HashMap<&'a RepoPath, BTreeMap>); + +impl<'a> CloneLineAnchors<'a> { + pub(crate) fn new(model: &'a SourceSetModel, duplication: &Duplication) -> Self { + let clone_paths: HashSet<_> = duplication + .clone_lines + .count_by_file() + .map(|(path, _)| path) + .collect(); + let hashes = model + .files + .iter() + .filter(|file| clone_paths.contains(&file.path)) + .map(|file| { + let path = file.path.as_str(); + let hash_start = StableHasher::new().write_bytes(b"codeint.clone-line.v1"); + let mut occurrences = HashMap::::new(); + let lines = file + .model + .tokens + .chunk_by(|left, right| left.line == right.line) + .filter_map(|tokens| { + let line = tokens[0].line; + let content = tokens + .iter() + .fold(hash_start, |hash, token| hash.write_u64(token.text_hash)) + .finish(); + let occurrence = occurrences.entry(content).or_default(); + *occurrence += 1; + duplication + .clone_lines + .contains(&file.path, line) + .then(|| (line, CloneLineAnchor::new(path, *occurrence, content))) + }) + .collect(); + (&file.path, lines) + }) + .collect(); + Self(hashes) + } + + pub(crate) fn finding(&self, group: &CloneGroup) -> CloneGroupFinding { + let mut finding = CloneGroupFinding::from(group); + if let Some(anchor) = &mut finding.anchor { + anchor.clone_lines = group + .fragments + .iter() + .flat_map(|fragment| { + self.0.get(&fragment.path).into_iter().flat_map(|lines| { + lines + .range(fragment.start_line..=fragment.end_line) + .map(|(_, &hash)| hash) + }) + }) + .collect(); + anchor.clone_lines.sort_unstable(); + anchor.clone_lines.dedup(); + } + finding + } +} diff --git a/crates/report/src/findings.rs b/crates/report/src/findings.rs index b895439e..0a7afecf 100644 --- a/crates/report/src/findings.rs +++ b/crates/report/src/findings.rs @@ -523,6 +523,7 @@ impl From<&ExternalFinding> for ExternalMetricFinding { before: None, after: None, line: Some(finding.line), + clone_lines: Vec::new(), }); ExternalMetricFinding { id: finding.id.clone(), diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 98dc1c89..9deb63b7 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -94,6 +94,7 @@ mod baseline_listing; mod baseline_rows; mod check_run; mod churn; +mod clone_line_anchors; mod config; mod coupling; mod dependencies; diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index d0b14f97..ce226837 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -16,6 +16,7 @@ use codeint_model::{ use serde::{Deserialize, Serialize}; use crate::baseline::Identified; +use crate::clone_line_anchors::CloneLineAnchors; use crate::{ BoundaryFindingRow, CloneFamilyFinding, CloneGroupFinding, CognitiveComplexityFinding, ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, HazardLineRow, @@ -502,6 +503,7 @@ impl SourceSetMeasurement { .iter() .map(MetricBodyHash::body_hash) .collect(); + let clone_line_anchors = CloneLineAnchors::new(model, &measured.duplication); Ok(SourceSetMeasurement { files: model.files.len(), erosion: MetricMeasurement::from_items( @@ -534,7 +536,7 @@ impl SourceSetMeasurement { measured.duplication.ratio(), measured.duplication.clone_lines.count() as f64, &measured.duplication.clone_groups, - CloneGroupFinding::from, + |group| clone_line_anchors.finding(group), ) .with_file_numerators(map_file_numerators( measured diff --git a/crates/report/src/render.rs b/crates/report/src/render.rs index a3141757..1321b710 100644 --- a/crates/report/src/render.rs +++ b/crates/report/src/render.rs @@ -327,7 +327,17 @@ impl FindingsView<'_> { where R: From<&'a T> + OwnedFinding + Identified + BaselineWeight, { - let rows: Vec = items.iter().map(R::from).collect(); + self.baselined_rows(metric, items.iter().map(R::from).collect()) + } + + pub(crate) fn baselined_rows( + self, + metric: &str, + rows: Vec, + ) -> (Findings, HashSet) + where + R: OwnedFinding + Identified + BaselineWeight, + { let (visible, baselined, hidden_ids) = match self.baseline { Some(scope) => scope.split(metric, rows), None => (rows, Baselined::default(), HashSet::new()), diff --git a/crates/report/src/summary.rs b/crates/report/src/summary.rs index 3892bb6c..611a9033 100644 --- a/crates/report/src/summary.rs +++ b/crates/report/src/summary.rs @@ -15,6 +15,7 @@ use codeint_model::{ }; use crate::baseline::BaselineScope; +use crate::clone_line_anchors::CloneLineAnchors; use crate::findings::{ CloneFamilyFinding, clustered_clone_group_ids, unlisted_clone_family_group_ids, }; @@ -353,6 +354,7 @@ impl HazardsSection { impl DuplicationSection { fn new( + model: &SourceSetModel, duplication: &Duplication, ranges: &ReferenceRangeScope, view: FindingsView<'_>, @@ -371,8 +373,15 @@ impl DuplicationSection { None, ) }; - let (clone_groups, hidden_group_ids) = - view.map_baselined_with_hidden(Metric::Duplication.key(), &duplication.clone_groups); + let anchors = CloneLineAnchors::new(model, duplication); + let (clone_groups, hidden_group_ids) = view.baselined_rows( + Metric::Duplication.key(), + duplication + .clone_groups + .iter() + .map(|group| anchors.finding(group)) + .collect(), + ); let all_clone_families = view.ownership.apply( duplication .clone_families @@ -602,6 +611,7 @@ impl SourceSetSection { ), }, duplication: DuplicationSection::new( + model, &measured.duplication, ranges, view, diff --git a/docs/guide/adopting-on-an-existing-codebase.md b/docs/guide/adopting-on-an-existing-codebase.md index ab3a413a..d062bf41 100644 --- a/docs/guide/adopting-on-an-existing-codebase.md +++ b/docs/guide/adopting-on-an-existing-codebase.md @@ -111,6 +111,7 @@ See [`codeint ratchet`](../reference.md#codeint-ratchet). ## The Baseline: `.codeint/baseline.json` The Baseline stores each existing Finding's identifier and hashed surrounding-line context anchors (never raw source text), with the Metric version that produced it. +See [Duplication Baseline behavior](../reference.md#codeint-baseline) for how coverage survives changes to Clone groups. `codeint check` hides those Findings and both `codeint check` and `codeint diff` evaluate Budgets on the Findings that remain, pairing duplicate Findings by surrounding-line context so inserting an identical Finding above legacy code reports the new line. When a pull request renames or moves files, `codeint diff` detects those renames in process (controlled by `--rename-threshold`, defaulting to `50`) so moved files keep pre-existing Findings unchanged and baselined, skip `new_file_budgets`, and compare `per_file` numerators against their previous path. This lets you set a strict Budget, such as `"erosion": 0`, on day one without failing on legacy code; `codeint init --adopt` writes those zero Budgets for you. diff --git a/docs/reference.md b/docs/reference.md index 3f0c4c44..ffa167e3 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1093,6 +1093,11 @@ When `.codeint/baseline.json` exists, `codeint check` (including `--package` run `codeint check --ignore-baseline` ignores `.codeint/baseline.json`: it shows every Finding, evaluates Budgets on every Finding, and skips the Metric version check. When `.codeint/baseline.json` exists, `codeint diff` also compares each head Budget with the non-baselined ratio. +New Duplication Baseline entries store hashed clone line occurrences. +An unchanged occurrence stays covered when a Clone group loses a member or overlapping spans combine. +The Duplication Budget counts only uncovered clone lines, and the report hides groups whose lines are all covered. +Older entries still match by Clone group. +To record occurrence coverage, create a new Baseline or use `codeint baseline update --reset` to replace the existing Baseline. Zero Budgets written by `codeint init --adopt` therefore pass on clean pull requests and fail on any new Finding. When a Baseline Metric version differs from the current Metric version, `codeint diff` stops with exit code 2 and names `codeint baseline update`. Base-versus-head Finding classification, Regressions, per-file checks, new-file Budgets, and Ratchet enforcement stay unchanged. diff --git a/docs/verification/features/baseline.md b/docs/verification/features/baseline.md index af00c99b..02b82f36 100644 --- a/docs/verification/features/baseline.md +++ b/docs/verification/features/baseline.md @@ -26,6 +26,13 @@ docs/verification/verify.sh doctor "$RUN_DIR" | `corrupt_refused` | `.codeint/baseline.json` holds invalid JSON, then `codeint baseline update` | `2` | Standard error reports invalid Baseline JSON | | `corrupt_reset` | `codeint baseline update --reset --format json` on the corrupt file | `0` | JSON reports `replaced_invalid: true`; `.codeint/baseline.json` is valid JSON again | +## Duplication + +Run `cargo test --locked -p codeint --test integration baseline::duplication_baseline`. +The tests use temporary Git repositories with an exact-clone zero Budget and three files with overlapping duplicate spans. +They verify that replacing one file reduces measured clone lines from 56 to 40, keeps the surviving spans covered, and allows a normal Baseline update. +They also verify that copying a clone into a new file fails the Budget and that `codeint state check` rejects added coverage. + ## Drive and Assert ```sh From 9a7655b31543aa9157f1f5d213df1e31d5e3d76e Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 00:07:13 +0800 Subject: [PATCH 2/3] fix(report): upgrade existing clone Baselines without a reset Convert unchanged group IDs to line coverage. Verify the upgrade against the base commit before accepting it in state check. --- crates/cli/HOW-TO.md | 3 +- crates/cli/src/check.rs | 1 + crates/cli/src/remedy.rs | 1 + crates/cli/src/state.rs | 64 ++++++++++++++++++- crates/cli/tests/integration/baseline.rs | 59 +++++++++++++++++ crates/config/src/baseline.rs | 20 +++++- crates/report/src/measurement.rs | 10 +++ .../guide/adopting-on-an-existing-codebase.md | 3 +- docs/reference.md | 7 +- 9 files changed, 159 insertions(+), 9 deletions(-) diff --git a/crates/cli/HOW-TO.md b/crates/cli/HOW-TO.md index 6f2ce980..21987396 100644 --- a/crates/cli/HOW-TO.md +++ b/crates/cli/HOW-TO.md @@ -21,7 +21,8 @@ if !outcome.passed { - `run_cli` returns exit code `0` on pass, `1` when any Budget, Ratchet, Regression, `state check` violation, `doctor` blocking error, or `plugin test` check fails, and `2` on operational errors. - Library entry points in `src/lib.rs` (`check`, `diff`, `trend`, `impact`, `trace`, `init`, `guard`, `state_check`, `schema`, `resolved_config`, `doctor`, `agent_status`, `agent_install`, `churn`, `coupling`, `ratchet_update`, `baseline_update`, `rerender_report`, `plugin_test`) return `Result<_, CodeintError>` (except `schema`), where `CodeintError` pairs `message()` with an actionable `remedy()`. - Gated operations (`check`, `diff`, `state_check`, `doctor`, and `plugin_test`) return `GatedOutcome` (aliased as `CheckOutcome`, `DiffOutcome`, `StateCheckOutcome`, `DoctorOutcome`, and `PluginTestOutcome`), which pairs `passed`, `failures`, `report`, and `rendered` (`Option`, populated when `DiffOptions.format` is set). -- `state_check` accepts `StateCheckOptions` (`head_ref`, `rename_threshold` defaulting to `50` with `0` disabling rename detection and values above `100` failing with `CodeintError`) and compares each revision's configured Ratchet file and `.codeint/baseline.json` against the merge-base without parsing source files or loading Plugins. +- `state_check` accepts `StateCheckOptions` (`head_ref`, `rename_threshold` defaulting to `50` with `0` disabling rename detection and values above `100` failing with `CodeintError`) and compares each revision's configured Ratchet file and `.codeint/baseline.json` against the merge-base. + It measures the base commit with built-in Language plugins only when validating a legacy Duplication Baseline upgrade. - `diff` accepts `DiffOptions` (including `format: Option` to populate `DiffOutcome.rendered` alongside the typed `DiffReport`, and `rename_threshold` defaulting to `50`, with `0` disabling rename detection and values above `100` failing with `CodeintError`). - `init` takes `InitOptions` (`format`, `adopt`, `plugin_host`) and returns `InitOutcome` (`configuration` plus optional `AdoptedFiles` when `adopt` is `true`). - `ratchet_update` and `baseline_update` accept `RatchetUpdateOptions` and `BaselineUpdateOptions` (both aliases of `StateUpdateOptions` with `reset`, `coverage_reports`, and `plugin_host`). diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index 4ec25cb2..b1bc7b77 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -50,6 +50,7 @@ pub(crate) fn built_in_languages() -> Vec { .collect() } +#[derive(Default)] pub(crate) struct LoadedPlugins { external_languages: Vec<(String, WasmLanguagePlugin)>, external_metrics: Vec<(String, WasmMetricPlugin)>, diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 8f92451b..a515aaf9 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -339,6 +339,7 @@ fn state_check_remedy(error: &StateCheckError) -> Cow<'static, str> { StateCheckError::Git(error) => Cow::Borrowed(git_remedy(error)), StateCheckError::Configuration(error) => configuration_file_remedy(error), StateCheckError::StateFile(error) => state_file_remedy(error), + StateCheckError::BaselineMeasurement(error) => check_remedy(error), StateCheckError::InvalidRenameThreshold { .. } => { Cow::Borrowed("Pass an integer from 0 to 100 for --rename-threshold.") } diff --git a/crates/cli/src/state.rs b/crates/cli/src/state.rs index 55e01878..4e9df4d8 100644 --- a/crates/cli/src/state.rs +++ b/crates/cli/src/state.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use codeint_config::{ @@ -7,9 +7,11 @@ use codeint_config::{ parse_configuration_files, }; use codeint_git::{GitError, Repository, Snapshot, SnapshotFileLookup}; -use codeint_model::RepoPath; +use codeint_model::{Metric, RepoPath, SourceSet}; use codeint_report::{BaseCommit, StateCheckReport}; +use crate::check::{CheckError, LoadedPlugins}; +use crate::commit_measurement::measure_all_languages_for_package; use crate::diff::{Refs, Sides, sides}; #[derive(Debug, thiserror::Error)] @@ -20,6 +22,8 @@ pub(crate) enum StateCheckError { Configuration(#[from] ConfigurationFileError), #[error(transparent)] StateFile(#[from] StateFileError), + #[error("cannot verify the Duplication Baseline upgrade: {0}")] + BaselineMeasurement(#[source] Box), #[error("rename threshold {threshold} is out of range (0..={MAX_RENAME_THRESHOLD})")] InvalidRenameThreshold { threshold: u8 }, #[error("invalid {file} path {path:?}")] @@ -67,7 +71,8 @@ pub(crate) fn check( )?; let base_snapshot = repository.commit(merge_base)?; - let base_state = load_revision_state(RevisionSource::Commit(&base_snapshot), "base commit")?; + let mut base_state = + load_revision_state(RevisionSource::Commit(&base_snapshot), "base commit")?; let head_state = load_head_state(&repository, head_commit)?; let renames = detect_baseline_renames( @@ -78,6 +83,9 @@ pub(crate) fn check( rename_threshold, )?; + if let (Some(base), Some(head)) = (&mut base_state.baseline, &head_state.baseline) { + verify_clone_anchor_upgrades(&base_snapshot, base, head)?; + } let comparison = compare_state( &base_state.ratchet_path, base_state.ratchet.as_ref(), @@ -99,6 +107,56 @@ pub(crate) fn check( )) } +fn verify_clone_anchor_upgrades( + base_snapshot: &Snapshot, + base: &mut Baseline, + head: &Baseline, +) -> Result<(), StateCheckError> { + let metric = Metric::Duplication.key(); + let upgraded_sets: Vec = base + .source_sets + .iter() + .into_iter() + .filter_map(|(source_set, entries)| { + let before = entries.get(metric)?; + let after = head.entry(Some(source_set), metric)?; + if before.metric_version != after.metric_version { + return None; + } + let legacy_ids: BTreeSet<_> = before + .findings + .iter() + .filter(|finding| finding.clone_lines.is_empty()) + .map(|finding| &finding.id) + .collect(); + after + .findings + .iter() + .any(|finding| !finding.clone_lines.is_empty() && legacy_ids.contains(&finding.id)) + .then_some(source_set) + }) + .collect(); + if upgraded_sets.is_empty() { + return Ok(()); + } + let configuration = + load_revision_configuration(RevisionSource::Commit(base_snapshot), "base commit")?; + let (_, measurement) = measure_all_languages_for_package( + base_snapshot, + &LoadedPlugins::default(), + &configuration, + None, + None, + ) + .map_err(|error| StateCheckError::BaselineMeasurement(Box::new(error)))?; + for source_set in upgraded_sets { + if let Some(entry) = base.source_sets.get_mut(source_set).get_mut(metric) { + entry.upgrade_clone_line_anchors(measurement.clone_group_anchors(source_set)); + } + } + Ok(()) +} + #[derive(Clone, Copy)] enum RevisionSource<'a> { Commit(&'a Snapshot), diff --git a/crates/cli/tests/integration/baseline.rs b/crates/cli/tests/integration/baseline.rs index d2b042fa..311052f9 100644 --- a/crates/cli/tests/integration/baseline.rs +++ b/crates/cli/tests/integration/baseline.rs @@ -97,6 +97,65 @@ fn duplication_baseline_covers_surviving_overlapping_clone_spans() { check_json(repo.path(), &["--all"], 0); } +#[test] +fn duplication_baseline_update_upgrades_legacy_groups_without_adding_finding_ids() { + let repo = duplication_repository(); + run_codeint_text(repo.path(), &["baseline", "update"], 0); + let mut old = baseline_file(repo.path()); + let old_entry = &mut old["source_sets"]["production"]["duplication"]; + let mut old_ids = Vec::new(); + for finding in old_entry["findings"].as_array_mut().expect("clone groups") { + let fields = finding.as_object_mut().expect("clone group"); + fields + .remove("clone_lines") + .expect("new Baseline has clone anchors"); + old_ids.push(fields["id"].clone()); + } + let metric_version = old_entry["metric_version"].clone(); + fs::write(repo.path().join(BASELINE_FILE), old.to_string()).expect("write legacy Baseline"); + run_git(repo.path(), &["add", BASELINE_FILE]); + run_git(repo.path(), &["commit", "-qm", "record legacy Baseline"]); + check_json(repo.path(), &["--all"], 0); + + run_codeint_text(repo.path(), &["baseline", "update"], 0); + let updated = baseline_file(repo.path()); + let entry = &updated["source_sets"]["production"]["duplication"]; + assert_eq!(entry["metric_version"], metric_version); + let groups = entry["findings"].as_array().expect("clone groups"); + assert_eq!( + groups + .iter() + .map(|group| group["id"].clone()) + .collect::>(), + old_ids + ); + assert!( + groups.iter().all(|group| { + group["clone_lines"] + .as_array() + .is_some_and(|lines| !lines.is_empty()) + }), + "plain Baseline update must add clone line anchors" + ); + run_codeint_text(repo.path(), &["state", "check", "HEAD"], 0); + + let mut widened = updated.clone(); + let lines = widened["source_sets"]["production"]["duplication"]["findings"][0]["clone_lines"] + .as_array_mut() + .expect("clone line anchors"); + let mut added = lines[0].clone(); + added["occurrence"] = json!(99); + lines.push(added); + let baseline_path = repo.path().join(BASELINE_FILE); + fs::write(&baseline_path, widened.to_string()).expect("write widened upgrade"); + run_codeint_text(repo.path(), &["state", "check", "HEAD"], 1); + fs::write(&baseline_path, updated.to_string()).expect("restore verified upgrade"); + + let replacement = include_str!("../fixtures/duplication-baseline/replacement.txt"); + write_repo_files(repo.path(), &[("c.ts", replacement)]); + check_json(repo.path(), &["--all"], 0); +} + #[test] fn duplication_baseline_does_not_cover_a_new_copy_of_a_baselined_clone() { let repo = duplication_repository(); diff --git a/crates/config/src/baseline.rs b/crates/config/src/baseline.rs index 038136f1..c5e95fa1 100644 --- a/crates/config/src/baseline.rs +++ b/crates/config/src/baseline.rs @@ -31,6 +31,20 @@ pub struct BaselineEntry { } impl BaselineEntry { + pub fn upgrade_clone_line_anchors(&mut self, measured: &[FindingAnchor]) { + let by_id: BTreeMap<_, _> = measured + .iter() + .map(|finding| (finding.id.as_str(), &finding.clone_lines)) + .collect(); + for finding in &mut self.findings { + if finding.clone_lines.is_empty() + && let Some(lines) = by_id.get(finding.id.as_str()) + { + finding.clone_lines.clone_from(lines); + } + } + } + pub fn covered_clone_lines( &self, renames: &BTreeMap, @@ -404,9 +418,11 @@ fn update_duplication( let mut findings: Vec<_> = matched .matched_pairs .iter() - .map(|&(_, current)| { + .map(|&(previous, current)| { let mut finding = item.findings[current].clone(); - finding.clone_lines.clear(); + if legacy[previous].id != finding.id { + finding.clone_lines.clear(); + } finding }) .collect(); diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index ce226837..01f145d8 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -219,6 +219,16 @@ impl MetricBodyHash for ImportCycle { } impl CommitMeasurement { + pub fn clone_group_anchors(&self, source_set: SourceSet) -> &[FindingAnchor] { + let measurement = match source_set { + SourceSet::Production => &self.production, + SourceSet::Test => &self.test, + SourceSet::Generated => &self.generated, + SourceSet::Vendored => &self.vendored, + }; + &measurement.duplication.finding_anchors + } + pub fn has_missing_body_hashes(&self) -> bool { let sets_missing = [ &self.production, diff --git a/docs/guide/adopting-on-an-existing-codebase.md b/docs/guide/adopting-on-an-existing-codebase.md index d062bf41..c60557b7 100644 --- a/docs/guide/adopting-on-an-existing-codebase.md +++ b/docs/guide/adopting-on-an-existing-codebase.md @@ -183,7 +183,8 @@ To prevent a pull request from raising Ratchet ceilings, deleting `.codeint/ratc codeint state check origin/main ``` -The command reads only Git state and `.codeint/` JSON files without parsing source files. +The command reads Git state and `.codeint/` JSON files. +See the [state check reference](../reference.md#codeint-state) for how it verifies legacy Duplication Baseline upgrades. It exits `0` for first-time adoption, tightening, Baseline removal, rename-matched moves, and Metric version upgrades, and exits `1` on any weakening. See [`codeint state`](../reference.md#codeint-state). diff --git a/docs/reference.md b/docs/reference.md index ffa167e3..659b7ef4 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1097,7 +1097,8 @@ New Duplication Baseline entries store hashed clone line occurrences. An unchanged occurrence stays covered when a Clone group loses a member or overlapping spans combine. The Duplication Budget counts only uncovered clone lines, and the report hides groups whose lines are all covered. Older entries still match by Clone group. -To record occurrence coverage, create a new Baseline or use `codeint baseline update --reset` to replace the existing Baseline. +Run `codeint baseline update` on the existing Baseline before editing clone spans to record anchors for unchanged Clone group IDs. +This upgrade keeps the same Metric version and adds no Finding IDs for Duplication. Zero Budgets written by `codeint init --adopt` therefore pass on clean pull requests and fail on any new Finding. When a Baseline Metric version differs from the current Metric version, `codeint diff` stops with exit code 2 and names `codeint baseline update`. Base-versus-head Finding classification, Regressions, per-file checks, new-file Budgets, and Ratchet enforcement stay unchanged. @@ -1113,7 +1114,9 @@ Base-versus-head Finding classification, Regressions, per-file checks, new-file | ------ | ------- | | `-h, --help` | Print the help of `codeint state` | -`codeint state check [PATH]` compares each revision's configured Ratchet file (`.codeint/ratchet.json` by default, or `ratchet.path` from that revision's configuration file) and `.codeint/baseline.json` in the working tree, or at `--head `, against the merge-base of `` without parsing source files or loading Plugins. +`codeint state check [PATH]` compares each revision's configured Ratchet file (`.codeint/ratchet.json` by default, or `ratchet.path` from that revision's configuration file) and `.codeint/baseline.json` in the working tree, or at `--head `, against the merge-base of ``. +It reads state files without parsing source files, except when verifying a legacy Duplication Baseline upgrade. +For the upgrade, it measures the base commit with built-in Language plugins to check that new anchors cover existing clone lines. Repository-contained file and directory symlinks resolve consistently across Git commits and the working tree, while escaping or broken symlinks fail with exit code 2. It passes with exit code 0 when state files are adopted for the first time, unchanged, tightened, upgraded across a Metric version change, or when `.codeint/baseline.json` is deleted. It fails with exit code 1 when `.codeint/ratchet.json` is deleted, a recorded Ratchet entry is removed, a Ratchet ceiling is raised at the same Metric version, or `.codeint/baseline.json` adds unmatched Findings at the same Metric version. From 955cbba8f813dc713a71ccd587f5e3c0a7b23b76 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 00:33:16 +0800 Subject: [PATCH 3/3] refactor(cli): keep state check below its erosion Budget --- crates/cli/src/state.rs | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/cli/src/state.rs b/crates/cli/src/state.rs index 4e9df4d8..2a386aef 100644 --- a/crates/cli/src/state.rs +++ b/crates/cli/src/state.rs @@ -58,11 +58,7 @@ pub(crate) fn check( }); } let repository = Repository::discover(folder)?; - let Sides { - merge_base, - head, - head_commit, - } = sides( + let revisions = sides( &repository, &Refs { base: base_ref, @@ -70,22 +66,38 @@ pub(crate) fn check( }, )?; + compare_revisions(&repository, base_ref, revisions, rename_threshold) +} + +fn compare_revisions( + repository: &Repository, + base_ref: &str, + revisions: Sides, + rename_threshold: u8, +) -> Result { + let Sides { + merge_base, + head, + head_commit, + } = revisions; let base_snapshot = repository.commit(merge_base)?; let mut base_state = load_revision_state(RevisionSource::Commit(&base_snapshot), "base commit")?; - let head_state = load_head_state(&repository, head_commit)?; + let head_state = load_head_state(repository, head_commit)?; let renames = detect_baseline_renames( - &repository, + repository, &base_snapshot, head_state.snapshot.as_ref(), base_state.baseline.is_some() && head_state.baseline.is_some(), rename_threshold, )?; - if let (Some(base), Some(head)) = (&mut base_state.baseline, &head_state.baseline) { - verify_clone_anchor_upgrades(&base_snapshot, base, head)?; - } + verify_clone_anchor_upgrades( + &base_snapshot, + base_state.baseline.as_mut(), + head_state.baseline.as_ref(), + )?; let comparison = compare_state( &base_state.ratchet_path, base_state.ratchet.as_ref(), @@ -109,9 +121,12 @@ pub(crate) fn check( fn verify_clone_anchor_upgrades( base_snapshot: &Snapshot, - base: &mut Baseline, - head: &Baseline, + base: Option<&mut Baseline>, + head: Option<&Baseline>, ) -> Result<(), StateCheckError> { + let (Some(base), Some(head)) = (base, head) else { + return Ok(()); + }; let metric = Metric::Duplication.key(); let upgraded_sets: Vec = base .source_sets