difflore-cli 0.2.0

Your AI coding agent learned public code, not your team's private decisions. difflore turns past PR reviews into source-backed local rules.
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
//! Windsurf hook adapter.
//!
//! Windsurf wraps every hook payload in a common envelope keyed by
//! `agent_action_name` with a `tool_info` object carrying per-event
//! detail. The envelope also carries `trajectory_id` / `execution_id`
//! as session IDs and (for command-like events) a `cwd`.
//!
//! Example stdin (`post_write_code`):
//!
//! ```json
//! {
//!   "agent_action_name": "post_write_code",
//!   "trajectory_id": "...",
//!   "execution_id": "...",
//!   "timestamp": "...",
//!   "tool_info": {
//!     "file_path": "src/foo.ts",
//!     "edits": [{ "old_string": "a", "new_string": "b" }]
//!   }
//! }
//! ```
//!
//! Event mapping:
//!
//!   | Windsurf action          | Canonical event           |
//!   |--------------------------|---------------------------|
//!   | `pre_user_prompt`        | `UserPromptSubmit`        |
//!   | `post_write_code`        | `PostToolUse { Write }`   |
//!   | `post_run_command`       | `PostToolUse { Bash }`    |
//!   | `post_mcp_tool_use`      | `PostToolUse { mcp_*  }`  |
//!   | `post_cascade_response`  | `Stop`                    |
//!   | `session_start` / `beforeAgentResponse` | `SessionStart` |
//!   | anything else            | error (CLI no-ops)        |
//!
//! Windsurf exit codes: 0 = success, 2 = block (pre-hooks only). We
//! never block, so the adapter output is always consumed with exit 0.
//! Output contract: Windsurf ignores extra fields on advisory hooks,
//! so we ship `{ "continue": true }` plus optional `context` / message
//! fields for downstream builds that honour them.

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::synth;
use super::types::{HookEvent, HookResult};
use super::{PayloadAdapter, PlatformAdapter};

pub struct WindsurfAdapter;

/// Typed view of Windsurf's stdin envelope. All fields optional; rejected only
/// when `agent_action_name` is absent (malformed payload).
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub(crate) struct WindsurfHookPayload {
    #[serde(default)]
    agent_action_name: Option<String>,
    #[serde(default)]
    trajectory_id: Option<String>,
    #[serde(default)]
    execution_id: Option<String>,
    #[serde(default)]
    tool_info: Option<Value>,
}

impl WindsurfHookPayload {
    fn into_canonical(self) -> Result<HookEvent, String> {
        let action = self
            .agent_action_name
            .as_deref()
            .ok_or_else(|| "missing agent_action_name".to_owned())?;
        // Windsurf's envelope carries the session identity at the top level,
        // not inside `tool_info`. `trajectory_id` is the stable per-session
        // key; `execution_id` is the fallback. Thread it into every event so
        // `observation::classify` can cluster Windsurf observations the same
        // way it does Claude Code ones. Empty strings are treated as absent.
        let session_id = non_empty(self.trajectory_id).or_else(|| non_empty(self.execution_id));
        let info = self.tool_info.as_ref();
        match action {
            // Windsurf has used both names for SessionStart; either triggers
            // the warmup path.
            "session_start" | "beforeAgentResponse" => Ok(HookEvent::SessionStart {
                cwd: extract_cwd(info),
                session_id,
            }),
            "pre_user_prompt" => {
                let cwd = extract_cwd(info);
                Ok(HookEvent::UserPromptSubmit {
                    prompt: info
                        .and_then(|v| v.get("user_prompt"))
                        .and_then(|v| v.as_str())
                        .unwrap_or_default()
                        .to_owned(),
                    session_id,
                    transcript_path: None,
                    cwd: (!cwd.trim().is_empty()).then_some(cwd),
                })
            }
            "post_write_code" => {
                let file_path = info
                    .and_then(|v| v.get("file_path"))
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let target_files = file_path.iter().cloned().collect();
                let (old_text, new_text) = extract_write_text(info);
                Ok(HookEvent::PostToolUse {
                    tool_name: "Write".to_owned(),
                    cwd: non_empty_cwd(info),
                    file_path,
                    target_files,
                    diff: synthesise_write_diff(info),
                    session_id,
                    new_text,
                    old_text,
                })
            }
            "post_run_command" => Ok(HookEvent::PostToolUse {
                tool_name: "Bash".to_owned(),
                cwd: non_empty_cwd(info),
                file_path: None,
                target_files: Vec::new(),
                diff: synthesise_command_diff(info),
                session_id,
                new_text: None,
                old_text: None,
            }),
            "post_mcp_tool_use" => Ok(HookEvent::PostToolUse {
                tool_name: info
                    .and_then(|v| v.get("mcp_tool_name"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("mcp_tool")
                    .to_owned(),
                cwd: non_empty_cwd(info),
                file_path: None,
                target_files: Vec::new(),
                diff: synthesise_mcp_diff(info),
                session_id,
                new_text: None,
                old_text: None,
            }),
            "post_cascade_response" => Ok(HookEvent::Stop {
                session_id,
                transcript_path: None,
                cwd: None,
            }),
            other => Err(format!("unsupported Windsurf hook action: {other}")),
        }
    }
}

fn extract_cwd(info: Option<&Value>) -> String {
    info.and_then(|v| v.get("cwd"))
        .and_then(|v| v.as_str())
        .unwrap_or_default()
        .to_owned()
}

fn non_empty_cwd(info: Option<&Value>) -> Option<String> {
    let cwd = extract_cwd(info);
    (!cwd.trim().is_empty()).then_some(cwd)
}

/// Drop a `Some("")`/whitespace-only id down to `None` so blank envelope
/// fields don't become empty session ids downstream.
fn non_empty(value: Option<String>) -> Option<String> {
    value.filter(|s| !s.trim().is_empty())
}

fn extract_write_text(info: Option<&Value>) -> (Option<String>, Option<String>) {
    let Some(info) = info else {
        return (None, None);
    };
    let (edit_old, edit_new) = synth::extract_edit_strings(Some(info));
    if edit_old.is_some() || edit_new.is_some() {
        return (edit_old, edit_new);
    }

    let old_text = info
        .get("old_code")
        .and_then(|v| v.as_str())
        .map(String::from);
    let new_text = info
        .get("new_code")
        .or_else(|| info.get("content"))
        .and_then(|v| v.as_str())
        .map(String::from);
    (old_text, new_text)
}

/// Synthesise a diff from `post_write_code`'s edits array, falling back to
/// `content` for whole-file writes when edits is missing.
fn synthesise_write_diff(info: Option<&Value>) -> Option<String> {
    let info = info?;
    if let Some(edits) = info.get("edits").and_then(|v| v.as_array()) {
        let mut out = String::new();
        for edit in edits {
            if let (Some(old), Some(new)) = (
                edit.get("old_string").and_then(|v| v.as_str()),
                edit.get("new_string").and_then(|v| v.as_str()),
            ) {
                synth::append_old_new(&mut out, old, new);
            }
        }
        if !out.is_empty() {
            return Some(out);
        }
    }
    if let Some(content) = info.get("content").and_then(|v| v.as_str()) {
        return Some(synth::diff_content(content));
    }
    None
}

/// Diff-like summary for `post_run_command`. Windsurf ships the command under
/// `command_line` with no output, so this is just `$ cmd`.
fn synthesise_command_diff(info: Option<&Value>) -> Option<String> {
    let cmd = info?.get("command_line").and_then(|v| v.as_str())?;
    synth::diff_shell(Some(cmd), None)
}

/// Summary for `post_mcp_tool_use`: flattens the tool arguments and result into
/// a text blob so the retriever can match on keywords inside MCP tool I/O.
fn synthesise_mcp_diff(info: Option<&Value>) -> Option<String> {
    let info = info?;
    let mut out = String::new();
    if let Some(args) = info.get("mcp_tool_arguments") {
        out.push_str("+ mcp_tool_arguments: ");
        out.push_str(&args.to_string());
        out.push('\n');
    }
    if let Some(res) = info.get("mcp_result") {
        out.push_str("+ mcp_result: ");
        out.push_str(&res.to_string());
        out.push('\n');
    }
    if out.is_empty() { None } else { Some(out) }
}

impl PayloadAdapter for WindsurfAdapter {
    type Raw = WindsurfHookPayload;
    const PARSE_LABEL: &'static str = "Windsurf";

    fn into_canonical(raw: Self::Raw) -> Result<HookEvent, String> {
        raw.into_canonical()
    }
}

impl PlatformAdapter for WindsurfAdapter {
    fn name(&self) -> &'static str {
        "windsurf"
    }

    fn parse_stdin(&self, raw: &str) -> Result<HookEvent, String> {
        Self::parse_stdin_default(raw)
    }

    fn format_output(&self, result: HookResult) -> String {
        // Advisory hooks in Windsurf ignore extra keys; include `continue` so
        // future builds that treat its absence as "block" still pass through.
        let mut obj = json!({ "continue": result.continue_ });
        if let Some(ctx) = result.additional_context {
            // Matches the Cursor key surface, so a future Windsurf build that
            // picks up `context` already receives it.
            obj["context"] = Value::String(ctx);
        }
        let _ = result.system_message;
        crate::support::util::json_compact_or(&obj, "{\"continue\":true}")
    }
}

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

    #[test]
    fn parse_before_agent_response_also_maps_to_session_start() {
        let adapter = WindsurfAdapter;
        let raw = r#"{"agent_action_name":"beforeAgentResponse","tool_info":{}}"#;
        if let HookEvent::SessionStart { .. } = adapter.parse_stdin(raw).unwrap() {
            // pass — cwd may be empty string, that's fine
        } else {
            panic!("expected SessionStart");
        }
    }

    #[test]
    fn parse_pre_user_prompt_extracts_prompt() {
        let adapter = WindsurfAdapter;
        let raw =
            r#"{"agent_action_name":"pre_user_prompt","tool_info":{"user_prompt":"hi there"}}"#;
        assert_eq!(
            adapter.parse_stdin(raw).unwrap(),
            HookEvent::UserPromptSubmit {
                prompt: "hi there".into(),
                session_id: None,
                transcript_path: None,
                cwd: None,
            }
        );
    }

    #[test]
    fn parse_post_write_code_collects_edits_into_diff() {
        let adapter = WindsurfAdapter;
        let raw = r#"{
            "agent_action_name": "post_write_code",
            "tool_info": {
                "file_path": "src/a.ts",
                "edits": [
                    { "old_string": "x", "new_string": "y" },
                    { "old_string": "1", "new_string": "2" }
                ]
            }
        }"#;
        if let HookEvent::PostToolUse {
            tool_name,
            file_path,
            diff,
            old_text,
            new_text,
            ..
        } = adapter.parse_stdin(raw).unwrap()
        {
            assert_eq!(tool_name, "Write");
            assert_eq!(file_path.as_deref(), Some("src/a.ts"));
            assert_eq!(old_text.as_deref(), Some("x\n\n1"));
            assert_eq!(new_text.as_deref(), Some("y\n\n2"));
            let d = diff.unwrap();
            assert!(d.contains("-x") && d.contains("+y"));
            assert!(d.contains("-1") && d.contains("+2"));
        } else {
            panic!("expected PostToolUse");
        }
    }

    #[test]
    fn parse_post_run_command_maps_to_bash() {
        let adapter = WindsurfAdapter;
        let raw = r#"{
            "agent_action_name": "post_run_command",
            "tool_info": { "command_line": "npm test", "cwd": "/w/p" }
        }"#;
        if let HookEvent::PostToolUse {
            tool_name,
            file_path,
            diff,
            ..
        } = adapter.parse_stdin(raw).unwrap()
        {
            assert_eq!(tool_name, "Bash");
            assert!(file_path.is_none());
            assert_eq!(diff.as_deref(), Some("$ npm test\n"));
        } else {
            panic!("expected PostToolUse");
        }
    }

    #[test]
    fn parse_post_mcp_tool_use_preserves_tool_name() {
        let adapter = WindsurfAdapter;
        let raw = r#"{
            "agent_action_name": "post_mcp_tool_use",
            "tool_info": {
                "mcp_server_name": "difflore",
                "mcp_tool_name": "search_rules",
                "mcp_tool_arguments": {"diff": "foo"},
                "mcp_result": {"rules": []}
            }
        }"#;
        if let HookEvent::PostToolUse {
            tool_name, diff, ..
        } = adapter.parse_stdin(raw).unwrap()
        {
            assert_eq!(tool_name, "search_rules");
            let d = diff.unwrap();
            assert!(d.contains("mcp_tool_arguments"));
            assert!(d.contains("mcp_result"));
        } else {
            panic!("expected PostToolUse");
        }
    }

    #[test]
    fn trajectory_id_threads_into_session_id() {
        let adapter = WindsurfAdapter;
        let raw = r#"{
            "agent_action_name": "post_write_code",
            "trajectory_id": "traj-123",
            "execution_id": "exec-456",
            "tool_info": { "file_path": "src/a.ts", "content": "x" }
        }"#;
        if let HookEvent::PostToolUse { session_id, .. } = adapter.parse_stdin(raw).unwrap() {
            // trajectory_id wins over execution_id.
            assert_eq!(session_id.as_deref(), Some("traj-123"));
        } else {
            panic!("expected PostToolUse");
        }
    }

    #[test]
    fn execution_id_used_when_trajectory_id_absent() {
        let adapter = WindsurfAdapter;
        let raw = r#"{
            "agent_action_name": "post_cascade_response",
            "execution_id": "exec-456"
        }"#;
        if let HookEvent::Stop { session_id, .. } = adapter.parse_stdin(raw).unwrap() {
            assert_eq!(session_id.as_deref(), Some("exec-456"));
        } else {
            panic!("expected Stop");
        }
    }

    #[test]
    fn blank_session_ids_become_none() {
        let adapter = WindsurfAdapter;
        let raw = r#"{
            "agent_action_name": "session_start",
            "trajectory_id": "",
            "execution_id": "   ",
            "tool_info": {}
        }"#;
        if let HookEvent::SessionStart { session_id, .. } = adapter.parse_stdin(raw).unwrap() {
            assert!(session_id.is_none());
        } else {
            panic!("expected SessionStart");
        }
    }

    #[test]
    fn parse_unknown_action_errors() {
        let adapter = WindsurfAdapter;
        let err = adapter
            .parse_stdin(r#"{"agent_action_name":"post_future_thing","tool_info":{}}"#)
            .unwrap_err();
        assert!(err.contains("unsupported"), "got: {err}");
    }

    #[test]
    fn parse_missing_action_errors() {
        let adapter = WindsurfAdapter;
        let err = adapter.parse_stdin(r"{}").unwrap_err();
        assert!(err.contains("missing"), "got: {err}");
    }

    #[test]
    fn format_output_noop_emits_continue() {
        let adapter = WindsurfAdapter;
        let out = adapter.format_output(HookResult::noop());
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["continue"], true);
    }

    #[test]
    fn format_output_omits_system_message() {
        let adapter = WindsurfAdapter;
        let mut result = HookResult::noop();
        result.system_message = Some("DiffLore lifecycle note".to_owned());

        let out = adapter.format_output(result);
        let v: Value = serde_json::from_str(&out).unwrap();
        assert!(v.get("systemMessage").is_none());
    }

    #[test]
    fn format_output_with_context_adds_context_field() {
        let adapter = WindsurfAdapter;
        let out = adapter.format_output(HookResult::with_context("rule"));
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["context"], "rule");
    }
}