Skip to main content

lean_ctx/core/contextops/
drift.rs

1use std::path::Path;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6pub enum DriftStatus {
7    InSync,
8    Drifted,
9    Missing,
10    NoMarkers,
11    ReadError,
12    NotDetected,
13}
14
15impl std::fmt::Display for DriftStatus {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        match self {
18            Self::InSync => write!(f, "IN_SYNC"),
19            Self::Drifted => write!(f, "DRIFTED"),
20            Self::Missing => write!(f, "MISSING"),
21            Self::NoMarkers => write!(f, "NO_MARKERS"),
22            Self::ReadError => write!(f, "READ_ERROR"),
23            Self::NotDetected => write!(f, "NOT_DETECTED"),
24        }
25    }
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct DriftReport {
30    pub target: String,
31    pub path: String,
32    pub status: DriftStatus,
33    pub diff: Option<String>,
34}
35
36/// Compare each detected agent's on-disk `<!-- lean-ctx-rules -->` block against
37/// the **canonical** rule source (`rules_canonical` via
38/// `rules_inject::rules_shared_content` / `rules_dedicated_markdown`).
39///
40/// Drift is measured purely against the canonical single-source-of-truth — it
41/// deliberately does **not** read `.lean-ctx/rules.toml`. `rules.toml` is a
42/// `rules lint` input and a user-facing export from `rules init`; it never
43/// overrides the canonical rule body (see [`super::config::RulesConfig`]). This
44/// is also why `rules diff` works without running `rules init` first (#548).
45pub fn detect_drift(home: &Path) -> Vec<DriftReport> {
46    let statuses = crate::rules_inject::collect_rules_status(home);
47    // The canonical block lean-ctx would write for each target, keyed by name and
48    // chosen by the target's real `RulesFormat` — see the heuristic note below.
49    let expected_by_target = crate::rules_inject::expected_blocks_by_target(home);
50
51    let marker = crate::core::rules_canonical::START_MARK;
52    let end_marker = crate::core::rules_canonical::END_MARK;
53
54    statuses
55        .into_iter()
56        .map(|status| {
57            if !status.detected {
58                return DriftReport {
59                    target: status.name,
60                    path: status.path,
61                    status: DriftStatus::NotDetected,
62                    diff: None,
63                };
64            }
65
66            let path = Path::new(&status.path);
67            if !path.exists() {
68                return DriftReport {
69                    target: status.name,
70                    path: status.path,
71                    status: DriftStatus::Missing,
72                    diff: None,
73                };
74            }
75
76            let Ok(content) = std::fs::read_to_string(path) else {
77                return DriftReport {
78                    target: status.name,
79                    path: status.path,
80                    status: DriftStatus::ReadError,
81                    diff: None,
82                };
83            };
84
85            if !content.contains(marker) {
86                return DriftReport {
87                    target: status.name,
88                    path: status.path,
89                    status: DriftStatus::NoMarkers,
90                    diff: None,
91                };
92            }
93
94            let section = extract_section(&content, marker, end_marker);
95
96            // Compare against the canonical block for THIS target's format. The
97            // previous content heuristic ("up_to_date and no 'existing user
98            // rules'") misclassified freshly synced shared files (Copilot/Codex
99            // CLI) as dedicated and reported phantom drift after every sync (#548).
100            let expected_section = expected_by_target
101                .get(&status.name)
102                .map(|expected| extract_section(expected, marker, end_marker))
103                .unwrap_or_default();
104
105            let section_trimmed = section.trim();
106            let expected_trimmed = expected_section.trim();
107
108            if section_trimmed == expected_trimmed {
109                DriftReport {
110                    target: status.name,
111                    path: status.path,
112                    status: DriftStatus::InSync,
113                    diff: None,
114                }
115            } else {
116                let diff = compute_diff(expected_trimmed, section_trimmed);
117                DriftReport {
118                    target: status.name,
119                    path: status.path,
120                    status: DriftStatus::Drifted,
121                    diff: Some(diff),
122                }
123            }
124        })
125        .collect()
126}
127
128fn extract_section(content: &str, marker: &str, end_marker: &str) -> String {
129    let Some(start) = content.find(marker) else {
130        return String::new();
131    };
132    let end = content[start..]
133        .find(end_marker)
134        .map_or(content.len(), |e| start + e + end_marker.len());
135
136    content[start..end].to_string()
137}
138
139fn compute_diff(expected: &str, actual: &str) -> String {
140    let expected_lines: Vec<&str> = expected.lines().collect();
141    let actual_lines: Vec<&str> = actual.lines().collect();
142
143    let mut diff_lines = Vec::new();
144    let max_len = expected_lines.len().max(actual_lines.len());
145
146    for i in 0..max_len {
147        match (expected_lines.get(i), actual_lines.get(i)) {
148            (Some(exp), Some(act)) if exp != act => {
149                diff_lines.push(format!("- {exp}"));
150                diff_lines.push(format!("+ {act}"));
151            }
152            (Some(exp), None) => {
153                diff_lines.push(format!("- {exp}"));
154            }
155            (None, Some(act)) => {
156                diff_lines.push(format!("+ {act}"));
157            }
158            _ => {}
159        }
160    }
161
162    diff_lines.join("\n")
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::core::rules_canonical::{END_MARK, START_MARK};
169
170    #[test]
171    fn drift_status_display() {
172        assert_eq!(DriftStatus::InSync.to_string(), "IN_SYNC");
173        assert_eq!(DriftStatus::Drifted.to_string(), "DRIFTED");
174        assert_eq!(DriftStatus::Missing.to_string(), "MISSING");
175        assert_eq!(DriftStatus::NoMarkers.to_string(), "NO_MARKERS");
176        assert_eq!(DriftStatus::ReadError.to_string(), "READ_ERROR");
177        assert_eq!(DriftStatus::NotDetected.to_string(), "NOT_DETECTED");
178    }
179
180    #[test]
181    fn extract_section_with_markers() {
182        let content =
183            format!("before\n{START_MARK}\n<!-- version: 1 -->\n\nrules\n{END_MARK}\nafter");
184        let section = extract_section(&content, START_MARK, END_MARK);
185        assert!(section.contains("rules"));
186        assert!(section.contains(START_MARK));
187        assert!(section.contains(END_MARK));
188        assert!(!section.contains("before"));
189        assert!(!section.contains("after"));
190    }
191
192    #[test]
193    fn extract_section_no_marker() {
194        let section = extract_section("no markers here", "MARKER", "END");
195        assert!(section.is_empty());
196    }
197
198    #[test]
199    fn compute_diff_identical() {
200        let diff = compute_diff("line1\nline2", "line1\nline2");
201        assert!(diff.is_empty());
202    }
203
204    #[test]
205    fn compute_diff_changed() {
206        let diff = compute_diff("line1\nline2", "line1\nline3");
207        assert!(diff.contains("- line2"));
208        assert!(diff.contains("+ line3"));
209    }
210
211    #[test]
212    fn compute_diff_added_line() {
213        let diff = compute_diff("line1", "line1\nline2");
214        assert!(diff.contains("+ line2"));
215    }
216
217    #[test]
218    fn compute_diff_removed_line() {
219        let diff = compute_diff("line1\nline2", "line1");
220        assert!(diff.contains("- line2"));
221    }
222}