Skip to main content

lean_ctx_ext/core/contextops/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2pub(crate) mod config;
3pub(crate) mod drift;
4pub(crate) mod lint;
5pub(crate) mod sync;
6
7pub(crate) use config::RulesConfig;
8pub use drift::{DriftReport, DriftStatus};
9pub use lint::{LintSeverity, LintWarning};
10pub(crate) use sync::SyncReport;
11
12use std::path::Path;
13
14pub struct ContextOps {
15    pub home: std::path::PathBuf,
16    pub project_root: std::path::PathBuf,
17}
18
19impl ContextOps {
20    pub fn new(home: &Path, project_root: &Path) -> Self {
21        Self {
22            home: home.to_path_buf(),
23            project_root: project_root.to_path_buf(),
24        }
25    }
26
27    /// Drift between each agent's on-disk rules block and the canonical source.
28    ///
29    /// Infallible: drift is computed against `rules_canonical` (always present in
30    /// the binary), **not** against `.lean-ctx/rules.toml`, so `rules diff` needs
31    /// no prior `rules init` and can never fail on a missing config (#548).
32    pub fn detect_drift(&self) -> Vec<DriftReport> {
33        drift::detect_drift(&self.home)
34    }
35
36    pub fn sync_all(&self) -> SyncReport {
37        sync::sync_all(&self.home)
38    }
39
40    pub fn sync_agent(&self, agent: &str) -> SyncReport {
41        sync::sync_agent(&self.home, agent)
42    }
43
44    pub fn lint(&self) -> Result<Vec<LintWarning>, String> {
45        let config = RulesConfig::load(&self.project_root)?;
46        Ok(lint::lint(&config, &self.home))
47    }
48
49    pub fn status(&self) -> Vec<crate::rules_inject::RulesTargetStatus> {
50        crate::rules_inject::collect_rules_status(&self.home)
51    }
52
53    pub fn init(&self) -> Result<RulesConfig, String> {
54        RulesConfig::init_from_existing(&self.project_root, &self.home)
55    }
56
57    pub fn has_config(&self) -> bool {
58        RulesConfig::config_path(&self.project_root).exists()
59    }
60}
61
62pub fn format_status(statuses: &[crate::rules_inject::RulesTargetStatus]) -> String {
63    let mut lines = Vec::new();
64    lines.push("Agent Rules Status:".to_string());
65    lines.push(String::new());
66
67    for s in statuses {
68        let icon = match s.state.as_str() {
69            "up_to_date" => "✓",
70            "outdated" => "⚠",
71            "missing" => "✗",
72            "not_detected" => "·",
73            _ => "?",
74        };
75        let detected = if s.detected { "" } else { " (not installed)" };
76        lines.push(format!("  [{icon}] {}{detected} — {}", s.name, s.state));
77    }
78
79    lines.join("\n")
80}
81
82pub fn format_drift(reports: &[DriftReport]) -> String {
83    let mut lines = Vec::new();
84    lines.push("Drift Report:".to_string());
85    lines.push(String::new());
86
87    for r in reports {
88        if r.status == DriftStatus::NotDetected {
89            continue;
90        }
91        lines.push(format!("  [{}] {} ({})", r.status, r.target, r.path));
92        if let Some(diff) = &r.diff {
93            for dl in diff.lines().take(10) {
94                lines.push(format!("    {dl}"));
95            }
96            let total = diff.lines().count();
97            if total > 10 {
98                lines.push(format!("    ... ({} more lines)", total - 10));
99            }
100        }
101    }
102
103    lines.join("\n")
104}
105
106pub fn format_lint(warnings: &[LintWarning]) -> String {
107    if warnings.is_empty() {
108        return "No lint issues found.".to_string();
109    }
110
111    let mut lines = Vec::new();
112    lines.push(format!("Lint Results ({} issues):", warnings.len()));
113    lines.push(String::new());
114
115    for w in warnings {
116        let target = w
117            .target
118            .as_deref()
119            .map(|t| format!(" [{t}]"))
120            .unwrap_or_default();
121        lines.push(format!(
122            "  [{severity}] {code}{target}: {msg}",
123            severity = w.severity,
124            code = w.code,
125            msg = w.message,
126        ));
127    }
128
129    lines.join("\n")
130}
131
132pub fn format_sync(report: &SyncReport) -> String {
133    let mut lines = Vec::new();
134    lines.push("Sync Report:".to_string());
135    lines.push(String::new());
136
137    if !report.synced.is_empty() {
138        lines.push(format!("  Synced: {}", report.synced.join(", ")));
139    }
140    if !report.skipped.is_empty() {
141        lines.push(format!("  Already in sync: {}", report.skipped.join(", ")));
142    }
143    if !report.errors.is_empty() {
144        lines.push(format!("  Errors: {}", report.errors.join(", ")));
145    }
146    if report.synced.is_empty() && report.skipped.is_empty() && report.errors.is_empty() {
147        lines.push("  No targets found.".to_string());
148    }
149
150    lines.join("\n")
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn context_ops_has_config_false() {
159        let ops = ContextOps::new(
160            Path::new("/tmp/fake"),
161            Path::new("/tmp/nonexistent_contextops"),
162        );
163        assert!(!ops.has_config());
164    }
165
166    // #548 criterion 2: `rules diff` must not require `.lean-ctx/rules.toml`.
167    // `detect_drift` is now infallible and compares against the canonical rule
168    // source, so a project with no rules.toml produces a (possibly empty) drift
169    // report instead of the old "No rules config found" hard error. Serialized
170    // against other tests that read/write the global `CLAUDE_CONFIG_DIR`.
171    #[test]
172    #[serial_test::serial(claude_config_dir)]
173    fn detect_drift_without_rules_toml_does_not_require_init() {
174        let home = tempfile::tempdir().unwrap();
175        let project = tempfile::tempdir().unwrap();
176        let claude_dir = home.path().join(".claude").to_string_lossy().into_owned();
177        let _g = crate::test_env::EnvVarGuard::set("CLAUDE_CONFIG_DIR", &claude_dir);
178
179        let ops = ContextOps::new(home.path(), project.path());
180        assert!(
181            !ops.has_config(),
182            "sandbox project must have no rules.toml for this regression test"
183        );
184
185        // The pre-#548 code path would have errored here on the missing config.
186        // Now it returns well-formed reports straight from the canonical source.
187        let reports = ops.detect_drift();
188        for r in &reports {
189            assert!(!r.target.is_empty(), "drift report missing a target name");
190        }
191    }
192
193    #[test]
194    fn format_status_output() {
195        let statuses = vec![crate::rules_inject::RulesTargetStatus {
196            name: "TestAgent".to_string(),
197            detected: true,
198            path: "/tmp/test".to_string(),
199            state: "up_to_date".to_string(),
200            note: None,
201        }];
202        let output = format_status(&statuses);
203        assert!(output.contains("✓"));
204        assert!(output.contains("TestAgent"));
205    }
206
207    #[test]
208    fn format_drift_skips_not_detected() {
209        let reports = vec![DriftReport {
210            target: "Ghost".to_string(),
211            path: "/tmp/ghost".to_string(),
212            status: DriftStatus::NotDetected,
213            diff: None,
214        }];
215        let output = format_drift(&reports);
216        assert!(!output.contains("Ghost"));
217    }
218
219    #[test]
220    fn format_lint_empty() {
221        let output = format_lint(&[]);
222        assert_eq!(output, "No lint issues found.");
223    }
224
225    #[test]
226    fn format_lint_with_warnings() {
227        let warnings = vec![LintWarning {
228            severity: LintSeverity::Warning,
229            code: "TEST".to_string(),
230            message: "test warning".to_string(),
231            target: Some("cursor".to_string()),
232        }];
233        let output = format_lint(&warnings);
234        assert!(output.contains("[WARNING]"));
235        assert!(output.contains("[cursor]"));
236    }
237
238    #[test]
239    fn format_sync_empty() {
240        let report = SyncReport {
241            synced: vec![],
242            skipped: vec![],
243            errors: vec![],
244        };
245        let output = format_sync(&report);
246        assert!(output.contains("No targets found"));
247    }
248
249    #[test]
250    fn format_sync_with_results() {
251        let report = SyncReport {
252            synced: vec!["Cursor".to_string()],
253            skipped: vec!["Claude Code".to_string()],
254            errors: vec![],
255        };
256        let output = format_sync(&report);
257        assert!(output.contains("Cursor"));
258        assert!(output.contains("Claude Code"));
259    }
260
261    /// `rules diff` must call the block `rules sync` just wrote current, or
262    /// the user is told to sync forever (Pi: its own AGENTS.md beside the
263    /// user's text).
264    #[test]
265    fn pi_rules_written_by_sync_report_in_sync() {
266        let _iso = crate::core::data_dir::isolated_data_dir();
267        crate::test_env::remove_var("LEAN_CTX_RULES_INJECTION");
268        let tmp = tempfile::tempdir().unwrap();
269        let home = tmp.path();
270        let pi_dir = home.join("custom-pi-agent");
271        let _pi = crate::test_env::EnvVarGuard::set(
272            "PI_CODING_AGENT_DIR",
273            pi_dir.to_string_lossy().as_ref(),
274        );
275        std::fs::create_dir_all(&pi_dir).unwrap();
276        std::fs::write(pi_dir.join("AGENTS.md"), "# My own rules\n").unwrap();
277
278        let result = crate::rules_inject::inject_rules_for_agent(home, "pi");
279        assert!(result.errors.is_empty(), "{result:?}");
280        assert_eq!(result.updated.len(), 1, "{result:?}");
281
282        let drift = drift::detect_drift(home);
283        let pi = drift
284            .iter()
285            .find(|report| report.target == "Pi Coding Agent")
286            .expect("Pi in the drift report");
287        assert_eq!(pi.status, DriftStatus::InSync, "{pi:?}");
288    }
289}