Skip to main content

evolve_adapters/
aider.rs

1//! Aider adapter.
2//!
3//! Uses `aider.conf.yml` as the configuration surface and a git post-commit
4//! hook for session signals. Sessions are identified by the commit SHA.
5
6use crate::signals::{ParsedSignal, SessionLog, SignalKind};
7use crate::traits::{Adapter, AdapterDetection, AdapterError};
8use async_trait::async_trait;
9use evolve_core::agent_config::AgentConfig;
10use evolve_core::ids::AdapterId;
11use std::path::{Path, PathBuf};
12use tokio::fs;
13
14const MANAGED_START: &str = "# evolve:start";
15const MANAGED_END: &str = "# evolve:end";
16const HOOK_MARKER: &str = "evolve record-aider";
17
18/// Aider integration.
19#[derive(Debug, Clone, Default)]
20pub struct AiderAdapter;
21
22impl AiderAdapter {
23    /// Construct.
24    pub fn new() -> Self {
25        Self
26    }
27
28    fn conf_path(root: &Path) -> PathBuf {
29        root.join("aider.conf.yml")
30    }
31
32    fn post_commit_hook_path(root: &Path) -> PathBuf {
33        root.join(".git").join("hooks").join("post-commit")
34    }
35
36    /// Render a config as the YAML commentary that goes inside the managed section.
37    pub fn render_managed_section(config: &AgentConfig) -> String {
38        let mut out = String::new();
39        out.push_str("# System prompt prefix:\n");
40        for line in config.system_prompt_prefix.lines() {
41            out.push_str(&format!("#   {line}\n"));
42        }
43        if !config.behavioral_rules.is_empty() {
44            out.push_str("# Behavioral rules:\n");
45            for rule in &config.behavioral_rules {
46                out.push_str(&format!("#   - {rule}\n"));
47            }
48        }
49        out.push_str(&format!("# Response style: {:?}\n", config.response_style));
50        out.push_str(&format!("# Model preference: {:?}\n", config.model_pref));
51        out
52    }
53}
54
55#[async_trait]
56impl Adapter for AiderAdapter {
57    fn id(&self) -> AdapterId {
58        AdapterId::new("aider")
59    }
60
61    fn detect(&self, root: &Path) -> AdapterDetection {
62        if root.join("aider.conf.yml").is_file()
63            || root.join(".aider.conf.yml").is_file()
64            || root.join(".aider.tags.cache.v3").exists()
65        {
66            AdapterDetection::Detected
67        } else {
68            AdapterDetection::NotDetected
69        }
70    }
71
72    async fn install(&self, root: &Path, config: &AgentConfig) -> Result<(), AdapterError> {
73        // Write managed section into aider.conf.yml.
74        self.apply_config(root, config).await?;
75
76        // Install post-commit hook if .git/hooks exists.
77        let hooks_dir = root.join(".git").join("hooks");
78        if !hooks_dir.is_dir() {
79            // Not a git repo — skip hook install but not an error.
80            return Ok(());
81        }
82        let hook_path = Self::post_commit_hook_path(root);
83        let existing = if hook_path.is_file() {
84            fs::read_to_string(&hook_path).await?
85        } else {
86            "#!/bin/sh\n".to_string()
87        };
88        if existing.contains(HOOK_MARKER) {
89            return Ok(());
90        }
91        let mut new_hook = existing.clone();
92        if !new_hook.ends_with('\n') {
93            new_hook.push('\n');
94        }
95        new_hook.push_str("# evolve:hook-start\n");
96        new_hook.push_str(&format!("{HOOK_MARKER} HEAD >/dev/null 2>&1 || true\n"));
97        new_hook.push_str("# evolve:hook-end\n");
98        fs::write(&hook_path, new_hook).await?;
99        Ok(())
100    }
101
102    async fn apply_config(&self, root: &Path, config: &AgentConfig) -> Result<(), AdapterError> {
103        let path = Self::conf_path(root);
104        let existing = if path.is_file() {
105            fs::read_to_string(&path).await?
106        } else {
107            String::new()
108        };
109        let new_section = Self::render_managed_section(config);
110        let updated = replace_managed_section(&existing, &new_section);
111        fs::write(&path, updated).await?;
112        Ok(())
113    }
114
115    async fn parse_session(&self, log: SessionLog) -> Result<Vec<ParsedSignal>, AdapterError> {
116        let (_sha, project_root) = match log {
117            SessionLog::GitCommit { sha, project_root } => (sha, project_root),
118            _ => {
119                return Err(AdapterError::Parse(
120                    "aider adapter expects GitCommit log".into(),
121                ));
122            }
123        };
124
125        // No baseline signal: emitting a "neutral 0.5" for every commit was
126        // misleading — it pulled the posterior towards 0.5 indefinitely for
127        // users who didn't configure test-cmd / lint-cmd, so experiments
128        // would Hold forever near indifference. Empty signal vec means the
129        // session aggregates to 0.5 (neutral prior) once, which is correct
130        // semantics for "no information".
131        let mut signals = Vec::new();
132
133        if let Some(root) = project_root.as_deref() {
134            let cmds = read_aider_cmds(root).await.unwrap_or_default();
135            if let Some(test_cmd) = cmds.test_cmd.as_deref() {
136                signals.push(run_and_signal(root, test_cmd, "aider_tests").await);
137            }
138            if let Some(lint_cmd) = cmds.lint_cmd.as_deref() {
139                signals.push(run_and_signal(root, lint_cmd, "aider_lint").await);
140            }
141        }
142        Ok(signals)
143    }
144
145    async fn forget(&self, root: &Path) -> Result<(), AdapterError> {
146        // Strip managed section from aider.conf.yml.
147        let conf = Self::conf_path(root);
148        if conf.is_file() {
149            let raw = fs::read_to_string(&conf).await?;
150            let stripped = strip_managed_section(&raw);
151            if stripped.trim().is_empty() {
152                fs::remove_file(&conf).await?;
153            } else {
154                fs::write(&conf, stripped).await?;
155            }
156        }
157        // Remove hook block.
158        let hook = Self::post_commit_hook_path(root);
159        if hook.is_file() {
160            let raw = fs::read_to_string(&hook).await?;
161            let stripped = raw
162                .lines()
163                .filter(|line| !line.contains(HOOK_MARKER) && !line.contains("evolve:hook-"))
164                .collect::<Vec<_>>()
165                .join("\n");
166            fs::write(&hook, stripped).await?;
167        }
168        Ok(())
169    }
170}
171
172#[derive(Debug, Default, Clone)]
173struct AiderCmds {
174    test_cmd: Option<String>,
175    lint_cmd: Option<String>,
176}
177
178/// Read `test-cmd:` and `lint-cmd:` values from `aider.conf.yml`.
179/// Minimal YAML parsing — looks only for `key: value` at column 0.
180async fn read_aider_cmds(root: &Path) -> Option<AiderCmds> {
181    let conf = root.join("aider.conf.yml");
182    if !conf.is_file() {
183        return None;
184    }
185    let raw = fs::read_to_string(&conf).await.ok()?;
186    let mut out = AiderCmds::default();
187    for line in raw.lines() {
188        let trimmed = line.trim_start();
189        if trimmed.starts_with('#') {
190            continue;
191        }
192        if let Some(rest) = trimmed.strip_prefix("test-cmd:") {
193            out.test_cmd = Some(rest.trim().trim_matches('"').to_string());
194        } else if let Some(rest) = trimmed.strip_prefix("lint-cmd:") {
195            out.lint_cmd = Some(rest.trim().trim_matches('"').to_string());
196        }
197    }
198    Some(out)
199}
200
201/// Run `cmd` in `root` and return a signal based on exit code.
202/// Uses a 60-second timeout; timeouts count as failure.
203async fn run_and_signal(root: &Path, cmd: &str, source_tag: &str) -> ParsedSignal {
204    use tokio::process::Command;
205    use tokio::time::{Duration, timeout};
206
207    let output = timeout(
208        Duration::from_secs(60),
209        if cfg!(windows) {
210            Command::new("cmd")
211                .arg("/C")
212                .arg(cmd)
213                .current_dir(root)
214                .output()
215        } else {
216            Command::new("sh")
217                .arg("-c")
218                .arg(cmd)
219                .current_dir(root)
220                .output()
221        },
222    )
223    .await;
224
225    let (value, source) = match output {
226        Ok(Ok(o)) if o.status.success() => (1.0, format!("{source_tag}_passed")),
227        Ok(Ok(_)) => (0.0, format!("{source_tag}_failed")),
228        Ok(Err(_)) | Err(_) => (0.0, format!("{source_tag}_error")),
229    };
230    ParsedSignal {
231        kind: SignalKind::Implicit,
232        source,
233        value,
234        payload_json: None,
235    }
236}
237
238fn replace_managed_section(existing: &str, new_body: &str) -> String {
239    let block = format!("{MANAGED_START}\n{}\n{MANAGED_END}", new_body.trim_end());
240    if let (Some(start), Some(end)) = (existing.find(MANAGED_START), existing.find(MANAGED_END)) {
241        if end > start {
242            let end_full = end + MANAGED_END.len();
243            let mut out = String::new();
244            out.push_str(&existing[..start]);
245            out.push_str(&block);
246            out.push_str(&existing[end_full..]);
247            return out;
248        }
249    }
250    let mut out = String::from(existing);
251    if !out.is_empty() && !out.ends_with('\n') {
252        out.push('\n');
253    }
254    if !out.is_empty() {
255        out.push('\n');
256    }
257    out.push_str(&block);
258    out.push('\n');
259    out
260}
261
262fn strip_managed_section(existing: &str) -> String {
263    if let (Some(start), Some(end)) = (existing.find(MANAGED_START), existing.find(MANAGED_END)) {
264        if end > start {
265            let end_full = end + MANAGED_END.len();
266            let mut out = String::new();
267            out.push_str(&existing[..start]);
268            out.push_str(existing[end_full..].trim_start_matches('\n'));
269            return out;
270        }
271    }
272    existing.to_string()
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use tempfile::TempDir;
279
280    fn sample_config() -> AgentConfig {
281        AgentConfig::default_for("aider")
282    }
283
284    #[tokio::test]
285    async fn detect_recognizes_aider_conf() {
286        let tmp = TempDir::new().unwrap();
287        std::fs::write(tmp.path().join("aider.conf.yml"), "model: gpt-4\n").unwrap();
288        assert_eq!(
289            AiderAdapter::new().detect(tmp.path()),
290            AdapterDetection::Detected
291        );
292    }
293
294    #[tokio::test]
295    async fn apply_config_writes_managed_section() {
296        let tmp = TempDir::new().unwrap();
297        AiderAdapter::new()
298            .apply_config(tmp.path(), &sample_config())
299            .await
300            .unwrap();
301        let raw = std::fs::read_to_string(tmp.path().join("aider.conf.yml")).unwrap();
302        assert!(raw.contains(MANAGED_START));
303        assert!(raw.contains("Response style"));
304    }
305
306    #[tokio::test]
307    async fn install_writes_post_commit_hook_when_git_repo() {
308        let tmp = TempDir::new().unwrap();
309        std::fs::create_dir_all(tmp.path().join(".git").join("hooks")).unwrap();
310        AiderAdapter::new()
311            .install(tmp.path(), &sample_config())
312            .await
313            .unwrap();
314        let hook =
315            std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
316                .unwrap();
317        assert!(hook.contains(HOOK_MARKER));
318    }
319
320    #[tokio::test]
321    async fn install_is_idempotent() {
322        let tmp = TempDir::new().unwrap();
323        std::fs::create_dir_all(tmp.path().join(".git").join("hooks")).unwrap();
324        let adapter = AiderAdapter::new();
325        adapter.install(tmp.path(), &sample_config()).await.unwrap();
326        let once =
327            std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
328                .unwrap();
329        adapter.install(tmp.path(), &sample_config()).await.unwrap();
330        let twice =
331            std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
332                .unwrap();
333        assert_eq!(once, twice);
334    }
335
336    #[tokio::test]
337    async fn parse_session_with_no_root_emits_no_signals() {
338        let signals = AiderAdapter::new()
339            .parse_session(SessionLog::GitCommit {
340                sha: "abc123".into(),
341                project_root: None,
342            })
343            .await
344            .unwrap();
345        // Without a project root we can't run test/lint cmds. Emit nothing
346        // rather than a misleading 0.5 baseline.
347        assert!(signals.is_empty());
348    }
349
350    #[tokio::test]
351    async fn parse_session_runs_test_cmd_when_configured() {
352        let tmp = TempDir::new().unwrap();
353        let ok_cmd = if cfg!(windows) { "exit 0" } else { "true" };
354        std::fs::write(
355            tmp.path().join("aider.conf.yml"),
356            format!("test-cmd: {ok_cmd}\n"),
357        )
358        .unwrap();
359        let signals = AiderAdapter::new()
360            .parse_session(SessionLog::GitCommit {
361                sha: "deadbeef".into(),
362                project_root: Some(tmp.path().to_path_buf()),
363            })
364            .await
365            .unwrap();
366        assert_eq!(signals.len(), 1);
367        assert_eq!(signals[0].source, "aider_tests_passed");
368        assert_eq!(signals[0].value, 1.0);
369    }
370
371    #[tokio::test]
372    async fn parse_session_emits_failed_signal_when_test_cmd_fails() {
373        let tmp = TempDir::new().unwrap();
374        let fail_cmd = if cfg!(windows) { "exit 1" } else { "false" };
375        std::fs::write(
376            tmp.path().join("aider.conf.yml"),
377            format!("test-cmd: {fail_cmd}\n"),
378        )
379        .unwrap();
380        let signals = AiderAdapter::new()
381            .parse_session(SessionLog::GitCommit {
382                sha: "c0ffee".into(),
383                project_root: Some(tmp.path().to_path_buf()),
384            })
385            .await
386            .unwrap();
387        assert_eq!(signals.len(), 1);
388        assert_eq!(signals[0].source, "aider_tests_failed");
389        assert_eq!(signals[0].value, 0.0);
390    }
391
392    #[tokio::test]
393    async fn parse_session_with_no_test_cmd_emits_no_signals() {
394        let tmp = TempDir::new().unwrap();
395        // aider.conf.yml exists but has no test-cmd / lint-cmd.
396        std::fs::write(tmp.path().join("aider.conf.yml"), "model: gpt-4\n").unwrap();
397        let signals = AiderAdapter::new()
398            .parse_session(SessionLog::GitCommit {
399                sha: "abc".into(),
400                project_root: Some(tmp.path().to_path_buf()),
401            })
402            .await
403            .unwrap();
404        assert!(signals.is_empty());
405    }
406
407    #[tokio::test]
408    async fn forget_removes_managed_section_and_hook() {
409        let tmp = TempDir::new().unwrap();
410        std::fs::create_dir_all(tmp.path().join(".git").join("hooks")).unwrap();
411        let adapter = AiderAdapter::new();
412        adapter.install(tmp.path(), &sample_config()).await.unwrap();
413        adapter.forget(tmp.path()).await.unwrap();
414        let hook =
415            std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
416                .unwrap();
417        assert!(!hook.contains(HOOK_MARKER));
418        // aider.conf.yml was created by install with only our section, so forget removes it
419        assert!(!tmp.path().join("aider.conf.yml").exists());
420    }
421}