evolve-adapters 0.3.0

Adapter trait + per-tool integrations (Claude Code, Cursor, Aider)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Claude Code adapter.

use crate::signals::{ParsedSignal, SessionLog, SignalKind};
use crate::traits::{Adapter, AdapterDetection, AdapterError};
use async_trait::async_trait;
use evolve_core::agent_config::AgentConfig;
use evolve_core::ids::AdapterId;
use serde_json::{Map, Value};
use std::path::{Path, PathBuf};
use tokio::fs;

const MANAGED_START: &str = "<!-- evolve:start -->";
const MANAGED_END: &str = "<!-- evolve:end -->";
const HOOK_MARKER: &str = "evolve record-claude-code";
const SESSION_START_MARKER: &str = "evolve session-start";

/// Claude Code integration.
#[derive(Debug, Clone, Default)]
pub struct ClaudeCodeAdapter;

impl ClaudeCodeAdapter {
    /// Construct.
    pub fn new() -> Self {
        Self
    }

    fn settings_path(root: &Path) -> PathBuf {
        root.join(".claude").join("settings.json")
    }

    fn claude_md_path(root: &Path) -> PathBuf {
        root.join("CLAUDE.md")
    }

    /// Public for tests: build the `Stop` hook object inserted into settings.json.
    pub fn stop_hook_entry() -> Value {
        serde_json::json!({
            "type": "command",
            "command": HOOK_MARKER,
        })
    }

    /// Public for tests: build the `SessionStart` hook object that flips the
    /// deployed variant according to the running experiment's traffic share.
    pub fn session_start_hook_entry() -> Value {
        serde_json::json!({
            "type": "command",
            "command": SESSION_START_MARKER,
        })
    }

    /// Render a config into the markdown snippet that goes inside
    /// the managed section of CLAUDE.md.
    pub fn render_managed_section(config: &AgentConfig) -> String {
        let mut out = String::new();
        out.push_str("# Evolve-managed configuration\n\n");
        out.push_str("## System prompt prefix\n\n");
        out.push_str(&config.system_prompt_prefix);
        out.push_str("\n\n");
        if !config.behavioral_rules.is_empty() {
            out.push_str("## Behavioral rules\n\n");
            for rule in &config.behavioral_rules {
                out.push_str(&format!("- {rule}\n"));
            }
            out.push('\n');
        }
        out.push_str(&format!(
            "## Response style\n\n{:?}\n\n",
            config.response_style
        ));
        out.push_str(&format!("## Model preference\n\n{:?}\n", config.model_pref));
        out
    }
}

#[async_trait]
impl Adapter for ClaudeCodeAdapter {
    fn id(&self) -> AdapterId {
        AdapterId::new("claude-code")
    }

    fn detect(&self, root: &Path) -> AdapterDetection {
        if root.join(".claude").is_dir()
            || root.join("CLAUDE.md").is_file()
            || root.join(".claude").join("settings.json").is_file()
        {
            AdapterDetection::Detected
        } else {
            AdapterDetection::NotDetected
        }
    }

    async fn install(&self, root: &Path, _config: &AgentConfig) -> Result<(), AdapterError> {
        let settings_path = Self::settings_path(root);
        if let Some(parent) = settings_path.parent() {
            fs::create_dir_all(parent).await?;
        }

        let mut settings: Value = if settings_path.is_file() {
            let raw = fs::read_to_string(&settings_path).await?;
            if raw.trim().is_empty() {
                Value::Object(Map::new())
            } else {
                serde_json::from_str(&raw)?
            }
        } else {
            Value::Object(Map::new())
        };

        // Idempotency: scan hooks.Stop[] for an entry whose command contains
        // our marker. If present, skip.
        let hooks = settings
            .as_object_mut()
            .expect("settings is an object")
            .entry("hooks".to_string())
            .or_insert_with(|| Value::Object(Map::new()));
        let hooks_obj = hooks
            .as_object_mut()
            .ok_or_else(|| AdapterError::Parse("hooks is not an object".into()))?;
        let stop = hooks_obj
            .entry("Stop".to_string())
            .or_insert_with(|| Value::Array(Vec::new()));
        let stop_arr = stop
            .as_array_mut()
            .ok_or_else(|| AdapterError::Parse("hooks.Stop is not an array".into()))?;

        let already = stop_arr.iter().any(|entry| {
            entry
                .get("command")
                .and_then(|c| c.as_str())
                .map(|s| s.contains(HOOK_MARKER))
                .unwrap_or(false)
        });
        if !already {
            stop_arr.push(Self::stop_hook_entry());
        }

        // Also install a SessionStart hook so the deployed variant can be
        // re-rolled per session (proper A/B). Idempotent.
        let start = hooks_obj
            .entry("SessionStart".to_string())
            .or_insert_with(|| Value::Array(Vec::new()));
        let start_arr = start
            .as_array_mut()
            .ok_or_else(|| AdapterError::Parse("hooks.SessionStart is not an array".into()))?;
        let start_already = start_arr.iter().any(|entry| {
            entry
                .get("command")
                .and_then(|c| c.as_str())
                .map(|s| s.contains(SESSION_START_MARKER))
                .unwrap_or(false)
        });
        if !start_already {
            start_arr.push(Self::session_start_hook_entry());
        }

        let rendered = serde_json::to_string_pretty(&settings)?;
        fs::write(&settings_path, rendered).await?;
        Ok(())
    }

    async fn apply_config(&self, root: &Path, config: &AgentConfig) -> Result<(), AdapterError> {
        let path = Self::claude_md_path(root);
        let existing = if path.is_file() {
            fs::read_to_string(&path).await?
        } else {
            String::new()
        };
        let new_section = Self::render_managed_section(config);
        let updated = replace_managed_section(&existing, &new_section);
        fs::write(&path, updated).await?;
        Ok(())
    }

    async fn parse_session(&self, log: SessionLog) -> Result<Vec<ParsedSignal>, AdapterError> {
        let path = match log {
            SessionLog::Transcript(p) => p,
            _ => return Err(AdapterError::Parse("expected Transcript log".into())),
        };
        let raw = fs::read_to_string(&path).await?;
        Ok(parse_transcript_lines(&raw))
    }

    async fn forget(&self, root: &Path) -> Result<(), AdapterError> {
        // Remove hook from settings.json (keep the file if other hooks exist).
        let settings_path = Self::settings_path(root);
        if settings_path.is_file() {
            let raw = fs::read_to_string(&settings_path).await?;
            if !raw.trim().is_empty() {
                let mut settings: Value = serde_json::from_str(&raw)?;
                for hook_name in ["Stop", "SessionStart"] {
                    if let Some(arr) = settings
                        .get_mut("hooks")
                        .and_then(|h| h.get_mut(hook_name))
                        .and_then(|s| s.as_array_mut())
                    {
                        arr.retain(|entry| {
                            entry
                                .get("command")
                                .and_then(|c| c.as_str())
                                .map(|s| {
                                    !s.contains(HOOK_MARKER) && !s.contains(SESSION_START_MARKER)
                                })
                                .unwrap_or(true)
                        });
                    }
                }
                fs::write(&settings_path, serde_json::to_string_pretty(&settings)?).await?;
            }
        }

        // Strip managed section from CLAUDE.md.
        let md_path = Self::claude_md_path(root);
        if md_path.is_file() {
            let raw = fs::read_to_string(&md_path).await?;
            let stripped = strip_managed_section(&raw);
            fs::write(&md_path, stripped).await?;
        }
        Ok(())
    }
}

/// Helper used by both real-schema and flat-schema user-message parsing to
/// emit the regex-driven feedback signals.
fn push_user_text_signals(
    text: &str,
    negative: &regex::Regex,
    positive: &regex::Regex,
    signals: &mut Vec<ParsedSignal>,
) {
    if text.trim() == "/clear" {
        signals.push(ParsedSignal {
            kind: SignalKind::Implicit,
            source: "user_clear".into(),
            value: 0.0,
            payload_json: None,
        });
        return;
    }
    if negative.is_match(text) {
        signals.push(ParsedSignal {
            kind: SignalKind::Implicit,
            source: "user_feedback_negative".into(),
            value: 0.3,
            payload_json: None,
        });
    }
    if positive.is_match(text) {
        signals.push(ParsedSignal {
            kind: SignalKind::Implicit,
            source: "user_feedback_positive".into(),
            value: 0.9,
            payload_json: None,
        });
    }
}

/// Replace (or insert) the managed section inside `existing`, returning the new content.
fn replace_managed_section(existing: &str, new_body: &str) -> String {
    let block = format!("{MANAGED_START}\n{}\n{MANAGED_END}", new_body.trim_end());
    if let (Some(start), Some(end)) = (existing.find(MANAGED_START), existing.find(MANAGED_END)) {
        if end > start {
            let end_full = end + MANAGED_END.len();
            let mut out = String::new();
            out.push_str(&existing[..start]);
            out.push_str(&block);
            out.push_str(&existing[end_full..]);
            return out;
        }
    }
    // No existing markers — append.
    let mut out = String::from(existing);
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    if !out.is_empty() {
        out.push('\n');
    }
    out.push_str(&block);
    out.push('\n');
    out
}

/// Remove the managed section entirely, leaving the rest of the file.
fn strip_managed_section(existing: &str) -> String {
    if let (Some(start), Some(end)) = (existing.find(MANAGED_START), existing.find(MANAGED_END)) {
        if end > start {
            let end_full = end + MANAGED_END.len();
            let mut out = String::new();
            out.push_str(&existing[..start]);
            out.push_str(existing[end_full..].trim_start_matches('\n'));
            return out;
        }
    }
    existing.to_string()
}

/// Parse a Claude Code transcript (JSONL) into signals.
///
/// Parse Claude Code transcript JSONL into signals.
///
/// Handles two schemas:
/// 1. **Real Anthropic Claude Code transcript:** events with
///    `{"type":"user"|"assistant","message":{"role":"...","content": ...}}`
///    where content is either a string or a list of content blocks
///    (`text`, `tool_use`, `tool_result`).
/// 2. **Flat schema** (used by some test fixtures and older transcripts):
///    `{"type":"user","text":"..."}`, `{"type":"tool_use","tool":"bash","exit_code":N}`.
///
/// Both produce the same signal vocabulary:
/// - `user_clear` (0.0) when `/clear` typed by user
/// - `user_feedback_positive` (0.9) / `user_feedback_negative` (0.3) by regex
/// - `tests_passed` (1.0) / `tests_failed` (0.0) by Bash exit code OR is_error
///   on a `tool_result` paired with a test-like command
/// - `subagent_ok` (1.0) / `subagent_fail` (0.0) for Task tool invocations
fn parse_transcript_lines(raw: &str) -> Vec<ParsedSignal> {
    use regex::Regex;

    let negative = Regex::new(r"(?i)\b(redo|wrong|no,? that|try again|undo)\b").unwrap();
    let positive = Regex::new(r"(?i)\b(thanks|perfect|looks good|lgtm|nice)\b").unwrap();
    let test_cmd =
        Regex::new(r"(?i)\b(cargo test|pytest|npm test|jest|go test|cargo check|cargo clippy)\b")
            .unwrap();

    // Track outstanding Bash tool_use ids so we can correlate their tool_result
    // (Anthropic transcript schema separates the two).
    let mut bash_test_ids: std::collections::HashMap<String, ()> = Default::default();
    let mut signals = Vec::new();

    for line in raw.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(event): Result<Value, _> = serde_json::from_str(line) else {
            continue;
        };
        let kind = event.get("type").and_then(|v| v.as_str()).unwrap_or("");
        match kind {
            "user" => {
                // Real schema: event.message.content is either a string or a list
                // of content blocks. Content blocks of type=tool_result indicate
                // a tool finished.
                let content = event.pointer("/message/content");
                if let Some(c) = content {
                    if let Some(text) = c.as_str() {
                        push_user_text_signals(text, &negative, &positive, &mut signals);
                    } else if let Some(arr) = c.as_array() {
                        for block in arr {
                            let btype = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
                            if btype == "text" {
                                let t = block.get("text").and_then(|v| v.as_str()).unwrap_or("");
                                push_user_text_signals(t, &negative, &positive, &mut signals);
                            } else if btype == "tool_result" {
                                let tool_use_id = block
                                    .get("tool_use_id")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or("");
                                if !bash_test_ids.contains_key(tool_use_id) {
                                    continue;
                                }
                                let is_error = block
                                    .get("is_error")
                                    .and_then(|v| v.as_bool())
                                    .unwrap_or(false);
                                signals.push(ParsedSignal {
                                    kind: SignalKind::Implicit,
                                    source: if !is_error {
                                        "tests_passed".into()
                                    } else {
                                        "tests_failed".into()
                                    },
                                    value: if !is_error { 1.0 } else { 0.0 },
                                    payload_json: None,
                                });
                                bash_test_ids.remove(tool_use_id);
                            }
                        }
                    }
                } else {
                    // Flat-schema fallback.
                    let text = event.get("text").and_then(|v| v.as_str()).unwrap_or("");
                    push_user_text_signals(text, &negative, &positive, &mut signals);
                }
            }
            "assistant" => {
                // Real schema: event.message.content is a list of blocks; we look
                // for tool_use blocks calling Bash with a test-like command, plus
                // Task tool calls (subagents).
                if let Some(arr) = event.pointer("/message/content").and_then(|c| c.as_array()) {
                    for block in arr {
                        let btype = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
                        if btype != "tool_use" {
                            continue;
                        }
                        let name = block.get("name").and_then(|v| v.as_str()).unwrap_or("");
                        let id = block
                            .get("id")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        if name.eq_ignore_ascii_case("bash") {
                            let cmd = block
                                .pointer("/input/command")
                                .and_then(|v| v.as_str())
                                .unwrap_or("");
                            if test_cmd.is_match(cmd) {
                                bash_test_ids.insert(id, ());
                            }
                        } else if name == "Task" {
                            let agent = block
                                .pointer("/input/subagent_type")
                                .and_then(|v| v.as_str())
                                .unwrap_or("unknown");
                            // Subagent outcomes arrive in the next user/tool_result;
                            // mark as observed for now via a neutral 0.5 if we never
                            // see the result. The real-schema test_passed/failed
                            // covers the bash case; for Task we emit a baseline OK
                            // so users can see it fired.
                            signals.push(ParsedSignal {
                                kind: SignalKind::Implicit,
                                source: "subagent_invoked".into(),
                                value: 0.5,
                                payload_json: Some(format!("{{\"subagent\":\"{agent}\"}}")),
                            });
                        }
                    }
                }
            }
            "tool_use" => {
                // Flat-schema fallback.
                let tool = event.get("tool").and_then(|v| v.as_str()).unwrap_or("");
                if tool != "bash" {
                    continue;
                }
                let cmd = event.get("command").and_then(|v| v.as_str()).unwrap_or("");
                if !test_cmd.is_match(cmd) {
                    continue;
                }
                let exit = event
                    .get("exit_code")
                    .and_then(|v| v.as_i64())
                    .unwrap_or(-1);
                signals.push(ParsedSignal {
                    kind: SignalKind::Implicit,
                    source: if exit == 0 {
                        "tests_passed".into()
                    } else {
                        "tests_failed".into()
                    },
                    value: if exit == 0 { 1.0 } else { 0.0 },
                    payload_json: None,
                });
            }
            "subagent" => {
                // Flat-schema fallback for explicit subagent events.
                let status = event.get("status").and_then(|v| v.as_str()).unwrap_or("");
                let agent = event
                    .get("subagent_type")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown");
                let (src, val) = match status {
                    "completed" | "success" => ("subagent_ok", 1.0),
                    "errored" | "failed" | "timeout" => ("subagent_fail", 0.0),
                    _ => continue,
                };
                signals.push(ParsedSignal {
                    kind: SignalKind::Implicit,
                    source: src.to_string(),
                    value: val,
                    payload_json: Some(format!("{{\"subagent\":\"{agent}\"}}")),
                });
            }
            _ => {}
        }
    }
    signals
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn sample_config() -> AgentConfig {
        AgentConfig::default_for("claude-code")
    }

    #[tokio::test]
    async fn detect_recognizes_claude_md() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("CLAUDE.md"), "# test").unwrap();
        let adapter = ClaudeCodeAdapter::new();
        assert_eq!(adapter.detect(tmp.path()), AdapterDetection::Detected);
    }

    #[tokio::test]
    async fn detect_returns_not_detected_for_empty_dir() {
        let tmp = TempDir::new().unwrap();
        let adapter = ClaudeCodeAdapter::new();
        assert_eq!(adapter.detect(tmp.path()), AdapterDetection::NotDetected);
    }

    #[tokio::test]
    async fn install_adds_stop_hook_to_fresh_settings() {
        let tmp = TempDir::new().unwrap();
        let adapter = ClaudeCodeAdapter::new();
        adapter.install(tmp.path(), &sample_config()).await.unwrap();
        let raw =
            std::fs::read_to_string(tmp.path().join(".claude").join("settings.json")).unwrap();
        assert!(raw.contains(HOOK_MARKER));
    }

    #[tokio::test]
    async fn install_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        let adapter = ClaudeCodeAdapter::new();
        adapter.install(tmp.path(), &sample_config()).await.unwrap();
        let first =
            std::fs::read_to_string(tmp.path().join(".claude").join("settings.json")).unwrap();
        adapter.install(tmp.path(), &sample_config()).await.unwrap();
        let second =
            std::fs::read_to_string(tmp.path().join(".claude").join("settings.json")).unwrap();
        assert_eq!(
            first, second,
            "second install must not change settings.json"
        );
    }

    #[tokio::test]
    async fn install_preserves_unrelated_settings() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join(".claude");
        std::fs::create_dir_all(&dir).unwrap();
        let existing = r#"{"theme":"dark","permissions":{"allow":["Bash"]}}"#;
        std::fs::write(dir.join("settings.json"), existing).unwrap();
        let adapter = ClaudeCodeAdapter::new();
        adapter.install(tmp.path(), &sample_config()).await.unwrap();
        let raw = std::fs::read_to_string(dir.join("settings.json")).unwrap();
        assert!(raw.contains("\"theme\""));
        assert!(raw.contains("\"permissions\""));
        assert!(raw.contains(HOOK_MARKER));
    }

    #[tokio::test]
    async fn apply_config_writes_managed_section_between_markers() {
        let tmp = TempDir::new().unwrap();
        let adapter = ClaudeCodeAdapter::new();
        adapter
            .apply_config(tmp.path(), &sample_config())
            .await
            .unwrap();
        let raw = std::fs::read_to_string(tmp.path().join("CLAUDE.md")).unwrap();
        assert!(raw.contains(MANAGED_START));
        assert!(raw.contains(MANAGED_END));
        assert!(raw.contains("System prompt prefix"));
    }

    #[tokio::test]
    async fn apply_config_preserves_user_content_outside_markers() {
        let tmp = TempDir::new().unwrap();
        let user_content = "# My own CLAUDE.md\n\nImportant project notes.\n";
        std::fs::write(tmp.path().join("CLAUDE.md"), user_content).unwrap();
        let adapter = ClaudeCodeAdapter::new();
        adapter
            .apply_config(tmp.path(), &sample_config())
            .await
            .unwrap();
        let raw = std::fs::read_to_string(tmp.path().join("CLAUDE.md")).unwrap();
        assert!(raw.contains("Important project notes."));
        assert!(raw.contains(MANAGED_START));
    }

    #[tokio::test]
    async fn apply_config_replaces_existing_managed_section() {
        let tmp = TempDir::new().unwrap();
        let initial =
            format!("# Keep\n\n{MANAGED_START}\nold content\n{MANAGED_END}\n\n# Also keep\n",);
        std::fs::write(tmp.path().join("CLAUDE.md"), &initial).unwrap();
        let adapter = ClaudeCodeAdapter::new();
        adapter
            .apply_config(tmp.path(), &sample_config())
            .await
            .unwrap();
        let raw = std::fs::read_to_string(tmp.path().join("CLAUDE.md")).unwrap();
        assert!(!raw.contains("old content"));
        assert!(raw.contains("# Keep"));
        assert!(raw.contains("# Also keep"));
    }

    #[tokio::test]
    async fn forget_removes_hook_but_keeps_other_hooks() {
        let tmp = TempDir::new().unwrap();
        let adapter = ClaudeCodeAdapter::new();
        // Seed with a foreign hook + evolve hook.
        adapter.install(tmp.path(), &sample_config()).await.unwrap();
        let path = tmp.path().join(".claude").join("settings.json");
        let raw = std::fs::read_to_string(&path).unwrap();
        let mut settings: Value = serde_json::from_str(&raw).unwrap();
        settings["hooks"]["Stop"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::json!({"type":"command","command":"other-thing"}));
        std::fs::write(&path, serde_json::to_string_pretty(&settings).unwrap()).unwrap();

        adapter.forget(tmp.path()).await.unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(!after.contains(HOOK_MARKER));
        assert!(after.contains("other-thing"));
    }

    #[tokio::test]
    async fn forget_strips_managed_section_preserves_user_text() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("CLAUDE.md");
        let content = format!("# User\n\n{MANAGED_START}\nmanaged\n{MANAGED_END}\n\n# Tail\n",);
        std::fs::write(&path, &content).unwrap();
        ClaudeCodeAdapter::new().forget(tmp.path()).await.unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(after.contains("# User"));
        assert!(after.contains("# Tail"));
        assert!(!after.contains("managed"));
    }

    // ----- transcript parsing -----

    fn jsonl(events: &[&str]) -> String {
        events.join("\n")
    }

    #[tokio::test]
    async fn parse_session_detects_user_clear() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("t.jsonl");
        std::fs::write(&path, jsonl(&[r#"{"type":"user","text":"/clear"}"#])).unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        assert_eq!(signals.len(), 1);
        assert_eq!(signals[0].source, "user_clear");
        assert_eq!(signals[0].value, 0.0);
    }

    #[tokio::test]
    async fn parse_session_detects_test_pass_and_fail() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("t.jsonl");
        std::fs::write(
            &path,
            jsonl(&[
                r#"{"type":"tool_use","tool":"bash","command":"cargo test","exit_code":0}"#,
                r#"{"type":"tool_use","tool":"bash","command":"cargo test","exit_code":1}"#,
            ]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        assert_eq!(signals.len(), 2);
        assert_eq!(signals[0].source, "tests_passed");
        assert_eq!(signals[0].value, 1.0);
        assert_eq!(signals[1].source, "tests_failed");
        assert_eq!(signals[1].value, 0.0);
    }

    #[tokio::test]
    async fn parse_session_detects_positive_and_negative_feedback() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("t.jsonl");
        std::fs::write(
            &path,
            jsonl(&[
                r#"{"type":"user","text":"perfect, thanks!"}"#,
                r#"{"type":"user","text":"no, that's wrong, redo"}"#,
            ]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        let sources: Vec<&str> = signals.iter().map(|s| s.source.as_str()).collect();
        assert!(sources.contains(&"user_feedback_positive"));
        assert!(sources.contains(&"user_feedback_negative"));
    }

    #[tokio::test]
    async fn parse_session_ignores_unrelated_bash_commands() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("t.jsonl");
        std::fs::write(
            &path,
            jsonl(&[r#"{"type":"tool_use","tool":"bash","command":"ls -la","exit_code":0}"#]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        assert!(signals.is_empty());
    }

    #[tokio::test]
    async fn parse_session_detects_subagent_completion() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("t.jsonl");
        std::fs::write(
            &path,
            jsonl(&[
                r#"{"type":"subagent","status":"completed","subagent_type":"code-reviewer"}"#,
                r#"{"type":"subagent","status":"errored","subagent_type":"debugger"}"#,
            ]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        assert_eq!(signals.len(), 2);
        assert_eq!(signals[0].source, "subagent_ok");
        assert_eq!(signals[0].value, 1.0);
        assert!(
            signals[0]
                .payload_json
                .as_deref()
                .unwrap()
                .contains("code-reviewer")
        );
        assert_eq!(signals[1].source, "subagent_fail");
        assert_eq!(signals[1].value, 0.0);
    }

    #[tokio::test]
    async fn parse_session_handles_real_anthropic_schema() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("real.jsonl");
        std::fs::write(
            &path,
            jsonl(&[
                // user with text-block content
                r#"{"type":"user","message":{"role":"user","content":[{"type":"text","text":"thanks, looks good"}]}}"#,
                // assistant invoking Bash with cargo test
                r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"command":"cargo test"}}]}}"#,
                // user message containing the tool_result for that bash call
                r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"ok","is_error":false}]}}"#,
            ]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        let sources: Vec<&str> = signals.iter().map(|s| s.source.as_str()).collect();
        assert!(sources.contains(&"user_feedback_positive"));
        assert!(sources.contains(&"tests_passed"));
    }

    #[tokio::test]
    async fn parse_session_real_schema_failed_test_emits_failed() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("realfail.jsonl");
        std::fs::write(
            &path,
            jsonl(&[
                r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_99","name":"Bash","input":{"command":"pytest"}}]}}"#,
                r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_99","content":"FAILED","is_error":true}]}}"#,
            ]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        let sources: Vec<&str> = signals.iter().map(|s| s.source.as_str()).collect();
        assert!(sources.contains(&"tests_failed"));
    }

    #[tokio::test]
    async fn parse_session_real_schema_task_subagent_invocation() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("subagent.jsonl");
        std::fs::write(
            &path,
            jsonl(&[
                r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"task_01","name":"Task","input":{"subagent_type":"code-reviewer","prompt":"review"}}]}}"#,
            ]),
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        assert_eq!(signals.len(), 1);
        assert_eq!(signals[0].source, "subagent_invoked");
        assert!(
            signals[0]
                .payload_json
                .as_deref()
                .unwrap()
                .contains("code-reviewer")
        );
    }

    #[tokio::test]
    async fn parse_session_tolerates_invalid_json_lines() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("t.jsonl");
        std::fs::write(
            &path,
            "not json\n{\"type\":\"user\",\"text\":\"/clear\"}\nalso not json",
        )
        .unwrap();
        let signals = ClaudeCodeAdapter::new()
            .parse_session(SessionLog::Transcript(path))
            .await
            .unwrap();
        assert_eq!(signals.len(), 1);
        assert_eq!(signals[0].source, "user_clear");
    }
}