Skip to main content

lean_ctx_ext/core/contextops/
drift.rs

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