1use 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#[derive(Debug, Clone, Default)]
20pub struct AiderAdapter;
21
22impl AiderAdapter {
23 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 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 self.apply_config(root, config).await?;
75
76 let hooks_dir = root.join(".git").join("hooks");
78 if !hooks_dir.is_dir() {
79 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 let mut signals = vec![ParsedSignal {
126 kind: SignalKind::Implicit,
127 source: "aider_commit_observed".into(),
128 value: 0.5,
129 payload_json: Some(format!("{{\"sha\":\"{sha}\"}}")),
130 }];
131
132 if let Some(root) = project_root.as_deref() {
133 let cmds = read_aider_cmds(root).await.unwrap_or_default();
134 if let Some(test_cmd) = cmds.test_cmd.as_deref() {
135 signals.push(run_and_signal(root, test_cmd, "aider_tests").await);
136 }
137 if let Some(lint_cmd) = cmds.lint_cmd.as_deref() {
138 signals.push(run_and_signal(root, lint_cmd, "aider_lint").await);
139 }
140 }
141 Ok(signals)
142 }
143
144 async fn forget(&self, root: &Path) -> Result<(), AdapterError> {
145 let conf = Self::conf_path(root);
147 if conf.is_file() {
148 let raw = fs::read_to_string(&conf).await?;
149 let stripped = strip_managed_section(&raw);
150 if stripped.trim().is_empty() {
151 fs::remove_file(&conf).await?;
152 } else {
153 fs::write(&conf, stripped).await?;
154 }
155 }
156 let hook = Self::post_commit_hook_path(root);
158 if hook.is_file() {
159 let raw = fs::read_to_string(&hook).await?;
160 let stripped = raw
161 .lines()
162 .filter(|line| !line.contains(HOOK_MARKER) && !line.contains("evolve:hook-"))
163 .collect::<Vec<_>>()
164 .join("\n");
165 fs::write(&hook, stripped).await?;
166 }
167 Ok(())
168 }
169}
170
171#[derive(Debug, Default, Clone)]
172struct AiderCmds {
173 test_cmd: Option<String>,
174 lint_cmd: Option<String>,
175}
176
177async fn read_aider_cmds(root: &Path) -> Option<AiderCmds> {
180 let conf = root.join("aider.conf.yml");
181 if !conf.is_file() {
182 return None;
183 }
184 let raw = fs::read_to_string(&conf).await.ok()?;
185 let mut out = AiderCmds::default();
186 for line in raw.lines() {
187 let trimmed = line.trim_start();
188 if trimmed.starts_with('#') {
189 continue;
190 }
191 if let Some(rest) = trimmed.strip_prefix("test-cmd:") {
192 out.test_cmd = Some(rest.trim().trim_matches('"').to_string());
193 } else if let Some(rest) = trimmed.strip_prefix("lint-cmd:") {
194 out.lint_cmd = Some(rest.trim().trim_matches('"').to_string());
195 }
196 }
197 Some(out)
198}
199
200async fn run_and_signal(root: &Path, cmd: &str, source_tag: &str) -> ParsedSignal {
203 use tokio::process::Command;
204 use tokio::time::{Duration, timeout};
205
206 let output = timeout(
207 Duration::from_secs(60),
208 if cfg!(windows) {
209 Command::new("cmd")
210 .arg("/C")
211 .arg(cmd)
212 .current_dir(root)
213 .output()
214 } else {
215 Command::new("sh")
216 .arg("-c")
217 .arg(cmd)
218 .current_dir(root)
219 .output()
220 },
221 )
222 .await;
223
224 let (value, source) = match output {
225 Ok(Ok(o)) if o.status.success() => (1.0, format!("{source_tag}_passed")),
226 Ok(Ok(_)) => (0.0, format!("{source_tag}_failed")),
227 Ok(Err(_)) | Err(_) => (0.0, format!("{source_tag}_error")),
228 };
229 ParsedSignal {
230 kind: SignalKind::Implicit,
231 source,
232 value,
233 payload_json: None,
234 }
235}
236
237fn replace_managed_section(existing: &str, new_body: &str) -> String {
238 let block = format!("{MANAGED_START}\n{}\n{MANAGED_END}", new_body.trim_end());
239 if let (Some(start), Some(end)) = (existing.find(MANAGED_START), existing.find(MANAGED_END)) {
240 if end > start {
241 let end_full = end + MANAGED_END.len();
242 let mut out = String::new();
243 out.push_str(&existing[..start]);
244 out.push_str(&block);
245 out.push_str(&existing[end_full..]);
246 return out;
247 }
248 }
249 let mut out = String::from(existing);
250 if !out.is_empty() && !out.ends_with('\n') {
251 out.push('\n');
252 }
253 if !out.is_empty() {
254 out.push('\n');
255 }
256 out.push_str(&block);
257 out.push('\n');
258 out
259}
260
261fn strip_managed_section(existing: &str) -> String {
262 if let (Some(start), Some(end)) = (existing.find(MANAGED_START), existing.find(MANAGED_END)) {
263 if end > start {
264 let end_full = end + MANAGED_END.len();
265 let mut out = String::new();
266 out.push_str(&existing[..start]);
267 out.push_str(existing[end_full..].trim_start_matches('\n'));
268 return out;
269 }
270 }
271 existing.to_string()
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277 use tempfile::TempDir;
278
279 fn sample_config() -> AgentConfig {
280 AgentConfig::default_for("aider")
281 }
282
283 #[tokio::test]
284 async fn detect_recognizes_aider_conf() {
285 let tmp = TempDir::new().unwrap();
286 std::fs::write(tmp.path().join("aider.conf.yml"), "model: gpt-4\n").unwrap();
287 assert_eq!(
288 AiderAdapter::new().detect(tmp.path()),
289 AdapterDetection::Detected
290 );
291 }
292
293 #[tokio::test]
294 async fn apply_config_writes_managed_section() {
295 let tmp = TempDir::new().unwrap();
296 AiderAdapter::new()
297 .apply_config(tmp.path(), &sample_config())
298 .await
299 .unwrap();
300 let raw = std::fs::read_to_string(tmp.path().join("aider.conf.yml")).unwrap();
301 assert!(raw.contains(MANAGED_START));
302 assert!(raw.contains("Response style"));
303 }
304
305 #[tokio::test]
306 async fn install_writes_post_commit_hook_when_git_repo() {
307 let tmp = TempDir::new().unwrap();
308 std::fs::create_dir_all(tmp.path().join(".git").join("hooks")).unwrap();
309 AiderAdapter::new()
310 .install(tmp.path(), &sample_config())
311 .await
312 .unwrap();
313 let hook =
314 std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
315 .unwrap();
316 assert!(hook.contains(HOOK_MARKER));
317 }
318
319 #[tokio::test]
320 async fn install_is_idempotent() {
321 let tmp = TempDir::new().unwrap();
322 std::fs::create_dir_all(tmp.path().join(".git").join("hooks")).unwrap();
323 let adapter = AiderAdapter::new();
324 adapter.install(tmp.path(), &sample_config()).await.unwrap();
325 let once =
326 std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
327 .unwrap();
328 adapter.install(tmp.path(), &sample_config()).await.unwrap();
329 let twice =
330 std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
331 .unwrap();
332 assert_eq!(once, twice);
333 }
334
335 #[tokio::test]
336 async fn parse_session_emits_commit_observed_signal() {
337 let signals = AiderAdapter::new()
338 .parse_session(SessionLog::GitCommit {
339 sha: "abc123".into(),
340 project_root: None,
341 })
342 .await
343 .unwrap();
344 assert_eq!(signals.len(), 1);
345 assert_eq!(signals[0].source, "aider_commit_observed");
346 assert!(
347 signals[0]
348 .payload_json
349 .as_deref()
350 .unwrap()
351 .contains("abc123")
352 );
353 }
354
355 #[tokio::test]
356 async fn forget_removes_managed_section_and_hook() {
357 let tmp = TempDir::new().unwrap();
358 std::fs::create_dir_all(tmp.path().join(".git").join("hooks")).unwrap();
359 let adapter = AiderAdapter::new();
360 adapter.install(tmp.path(), &sample_config()).await.unwrap();
361 adapter.forget(tmp.path()).await.unwrap();
362 let hook =
363 std::fs::read_to_string(tmp.path().join(".git").join("hooks").join("post-commit"))
364 .unwrap();
365 assert!(!hook.contains(HOOK_MARKER));
366 assert!(!tmp.path().join("aider.conf.yml").exists());
368 }
369}