dirge-agent 0.19.16

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
//! Spawning abstraction for LSP server processes.
//!
//! `Spawner` is a tiny trait so the orchestrator can be tested without
//! launching real `rust-analyzer` / `pyright` / etc. processes in CI. The
//! real implementation ([`ProcessSpawner`]) does the obvious thing with
//! [`tokio::process::Command`]; tests use an in-memory mock that pairs the
//! client with a fake server task over `tokio::io::duplex`.

use std::path::{Path, PathBuf};

use futures::future::BoxFuture;
use serde_json::Value;
use tokio::io::{AsyncBufRead, AsyncWrite};

/// Result of a successful spawn: the async I/O halves the [`crate::lsp::rpc::RpcClient`]
/// will consume, the server-specific `initializationOptions` payload, and an
/// opaque guard that holds the child process alive (its `Drop` terminates).
pub struct Spawned {
    pub reader: Box<dyn AsyncBufRead + Send + Unpin>,
    pub writer: Box<dyn AsyncWrite + Send + Unpin>,
    pub init_options: Value,
    /// Whatever needs to live for the child's lifetime — typically a
    /// `tokio::process::Child` with `kill_on_drop(true)`. Opaque to the
    /// manager; dropped when the client is shut down.
    ///
    /// `Send + Sync` because the manager stores entries behind an `Arc` and
    /// passes them across `tokio::spawn` boundaries; both `Child` and
    /// `JoinHandle` already satisfy this.
    pub guard: Box<dyn std::any::Any + Send + Sync>,
}

/// Launches LSP server processes. Trait so the orchestrator can be unit-
/// tested with in-memory duplex pipes.
pub trait Spawner: Send + Sync + 'static {
    fn spawn<'a>(
        &'a self,
        server_id: &'a str,
        root: &'a Path,
    ) -> BoxFuture<'a, std::io::Result<Spawned>>;
}

/// Default `Spawner` for production. Resolves the binary name via `which`-
/// style PATH lookup and spawns it with stdin/stdout/stderr piped.
///
/// Knows nothing about LSP semantics — the orchestrator (Phase 4) chooses
/// the binary name + args based on the `server_id` and any user config.
pub struct ProcessSpawner {
    /// Maps `server_id` to the binary + args to launch. Populated from the
    /// builtin registry + user config when the manager is constructed.
    commands: std::collections::HashMap<String, ProcessCommand>,
}

#[derive(Clone, Debug)]
pub struct ProcessCommand {
    pub program: PathBuf,
    pub args: Vec<String>,
    pub env: Vec<(String, String)>,
    pub init_options: Value,
}

impl ProcessSpawner {
    pub fn new(commands: std::collections::HashMap<String, ProcessCommand>) -> Self {
        Self { commands }
    }

    /// Built-in command defaults for the v1 server set. Each entry is the
    /// program name + argv to launch. The actual `tokio::process::Command`
    /// resolves `program` via PATH at spawn time.
    pub fn default_commands() -> std::collections::HashMap<String, ProcessCommand> {
        let mut m = std::collections::HashMap::new();
        m.insert(
            "rust".to_string(),
            ProcessCommand {
                program: PathBuf::from("rust-analyzer"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "typescript".to_string(),
            ProcessCommand {
                program: PathBuf::from("typescript-language-server"),
                args: vec!["--stdio".to_string()],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "pyright".to_string(),
            ProcessCommand {
                program: PathBuf::from("pyright-langserver"),
                args: vec!["--stdio".to_string()],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "clojure-lsp".to_string(),
            ProcessCommand {
                program: PathBuf::from("clojure-lsp"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        // Audit M5 additions. Defaults assume the canonical binary on
        // PATH; users override via config `lsp.servers.<id>.command`.
        m.insert(
            "gopls".to_string(),
            ProcessCommand {
                program: PathBuf::from("gopls"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "jdtls".to_string(),
            ProcessCommand {
                // jdtls' launch script wraps a complex java invocation;
                // most distros ship a `jdtls` wrapper. Users with the
                // raw `eclipse.jdt.ls` jar must override via config.
                program: PathBuf::from("jdtls"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "clangd".to_string(),
            ProcessCommand {
                program: PathBuf::from("clangd"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "ruby-lsp".to_string(),
            ProcessCommand {
                program: PathBuf::from("ruby-lsp"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "bash-language-server".to_string(),
            ProcessCommand {
                program: PathBuf::from("bash-language-server"),
                args: vec!["start".to_string()],
                env: vec![],
                init_options: Value::Null,
            },
        );
        // Dafny CLI's built-in language server, over stdio. `dafny` (the
        // apphost on PATH) is equivalent to `dotnet Dafny.dll`; we default
        // to it for portability. Setups with only the DLL override via
        // config: `lsp.servers.dafny.command = ["dotnet", "C:/.../Dafny.dll",
        // "server", "--verify-on", "change"]`. `--verify-on change`
        // re-verifies (SMT) on every edit so diagnostics reflect proof
        // failures, not just parse/resolve errors.
        m.insert(
            "dafny".to_string(),
            ProcessCommand {
                program: PathBuf::from("dafny"),
                args: vec![
                    "server".to_string(),
                    "--verify-on".to_string(),
                    "change".to_string(),
                ],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m.insert(
            "cmake".to_string(),
            ProcessCommand {
                program: PathBuf::from("cmake-language-server"),
                args: vec![],
                env: vec![],
                init_options: Value::Null,
            },
        );
        m
    }
}

impl Spawner for ProcessSpawner {
    fn spawn<'a>(
        &'a self,
        server_id: &'a str,
        root: &'a Path,
    ) -> BoxFuture<'a, std::io::Result<Spawned>> {
        Box::pin(async move {
            let cmd = self.commands.get(server_id).ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!("no spawn command configured for LSP server {server_id:?}"),
                )
            })?;

            let mut command = tokio::process::Command::new(&cmd.program);
            command
                .args(&cmd.args)
                .current_dir(root)
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .kill_on_drop(true);
            for (k, v) in &cmd.env {
                command.env(k, v);
            }
            // dirge-wupp: isolate the server in its own session (no
            // controlling terminal, new process group) so it can't corrupt
            // dirge's TUI and so the ProcessGroupGuard below can SIGKILL its
            // whole subtree — `kill_on_drop` alone reaps only the direct
            // child, orphaning e.g. tsserver / jdtls's java worker.
            crate::child_guard::detach_session(&mut command);

            let mut child = command.spawn().map_err(|e| {
                std::io::Error::new(
                    e.kind(),
                    format!("failed to spawn LSP server {server_id:?}: {e}"),
                )
            })?;
            let stdin = child
                .stdin
                .take()
                .ok_or_else(|| std::io::Error::other("LSP server stdin pipe unavailable"))?;
            let stdout = child
                .stdout
                .take()
                .ok_or_else(|| std::io::Error::other("LSP server stdout pipe unavailable"))?;

            // Drain stderr in the background. LSP servers chatter on stderr
            // (rust-analyzer logs there) and a full pipe would block the
            // child after ~64 KB.
            if let Some(stderr) = child.stderr.take() {
                let server_id = server_id.to_string();
                tokio::spawn(async move {
                    use tokio::io::AsyncBufReadExt;
                    let mut reader = tokio::io::BufReader::new(stderr);
                    let mut buf = String::new();
                    loop {
                        buf.clear();
                        match reader.read_line(&mut buf).await {
                            Ok(0) => break, // EOF
                            Ok(_) => tracing::debug!(server = %server_id, "{}", buf.trim_end()),
                            Err(_) => break,
                        }
                    }
                });
            }

            let reader: Box<dyn AsyncBufRead + Send + Unpin> =
                Box::new(tokio::io::BufReader::new(stdout));
            let writer: Box<dyn AsyncWrite + Send + Unpin> = Box::new(stdin);

            // dirge-wupp: pgid == pid after `detach_session`, so a group
            // SIGKILL reaps the server AND its descendants. The guard is
            // FIRST in the tuple so it drops first — its `kill(-pgid)` fires
            // while the leader child is still un-reaped; the child's own
            // `kill_on_drop` then redundantly signals the (already dead)
            // direct child.
            let pg_guard = crate::child_guard::ProcessGroupGuard::from_pid(child.id());

            Ok(Spawned {
                reader,
                writer,
                init_options: cmd.init_options.clone(),
                guard: Box::new((pg_guard, child)),
            })
        })
    }
}

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

    /// Mock spawner that pairs the client with a fake LSP server task over
    /// duplex pipes. The fake task responds to `initialize` with empty
    /// capabilities and any other request with `result: null`.
    pub(crate) struct MockSpawner {
        spawn_calls: std::sync::Mutex<Vec<(String, PathBuf)>>,
        fail_for: std::sync::Mutex<std::collections::HashSet<String>>,
    }

    impl MockSpawner {
        pub fn new() -> Self {
            Self {
                spawn_calls: std::sync::Mutex::new(Vec::new()),
                fail_for: std::sync::Mutex::new(std::collections::HashSet::new()),
            }
        }

        pub fn fail_when_server_id(&self, server_id: &str) {
            self.fail_for.lock().unwrap().insert(server_id.to_string());
        }

        pub fn calls(&self) -> Vec<(String, PathBuf)> {
            self.spawn_calls.lock().unwrap().clone()
        }
    }

    impl Spawner for MockSpawner {
        fn spawn<'a>(
            &'a self,
            server_id: &'a str,
            root: &'a Path,
        ) -> BoxFuture<'a, std::io::Result<Spawned>> {
            Box::pin(async move {
                self.spawn_calls
                    .lock()
                    .unwrap()
                    .push((server_id.to_string(), root.to_path_buf()));

                if self.fail_for.lock().unwrap().contains(server_id) {
                    return Err(std::io::Error::other(format!(
                        "mock spawn refused for {server_id}"
                    )));
                }

                let (client_in, mut server_writer) = tokio::io::duplex(8192);
                let (mut server_reader, client_out) = tokio::io::duplex(8192);

                // Fake server task: respond to anything with a sensible reply.
                let fake_server = tokio::spawn(async move {
                    use crate::jsonrpc_framing::{decode_frame, encode_frame};
                    use serde_json::json;
                    let mut reader = tokio::io::BufReader::new(&mut server_reader);
                    loop {
                        let frame = match decode_frame(&mut reader).await {
                            Ok(b) => b,
                            Err(_) => break,
                        };
                        let req: Value = match serde_json::from_slice(&frame) {
                            Ok(v) => v,
                            Err(_) => continue,
                        };
                        if req.get("id").is_none() {
                            continue; // notification — no reply
                        }
                        let id = req["id"].clone();
                        let method = req["method"].as_str().unwrap_or("");
                        let result = if method == "initialize" {
                            json!({"capabilities": {}})
                        } else {
                            Value::Null
                        };
                        let resp = json!({"jsonrpc": "2.0", "id": id, "result": result});
                        if encode_frame(&mut server_writer, &serde_json::to_vec(&resp).unwrap())
                            .await
                            .is_err()
                        {
                            break;
                        }
                    }
                });

                Ok(Spawned {
                    reader: Box::new(tokio::io::BufReader::new(client_in)),
                    writer: Box::new(client_out),
                    init_options: Value::Null,
                    guard: Box::new(fake_server),
                })
            })
        }
    }

    #[tokio::test]
    async fn mock_spawner_responds_to_initialize() {
        use crate::lsp::init::initialize;
        use crate::lsp::rpc::RpcClient;
        use tokio::io::BufReader;

        let s = MockSpawner::new();
        let spawned = s.spawn("rust", Path::new("/tmp")).await.unwrap();
        // BufReader<Box<dyn AsyncBufRead>> doesn't make sense — the inner
        // reader already implements AsyncBufRead. Use the boxed reader
        // directly.
        let reader = BufReader::new(spawned.reader);
        let (rpc, _) = RpcClient::new(reader, spawned.writer);
        let result = initialize(&rpc, Path::new("/tmp"), Some(1), spawned.init_options).await;
        assert!(result.is_ok(), "initialize should succeed: {result:?}");
    }

    #[tokio::test]
    async fn mock_spawner_records_calls() {
        let s = MockSpawner::new();
        let _ = s.spawn("rust", Path::new("/tmp")).await.unwrap();
        let _ = s.spawn("typescript", Path::new("/tmp/proj")).await.unwrap();
        let calls = s.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].0, "rust");
        assert_eq!(calls[1].0, "typescript");
    }

    #[tokio::test]
    async fn mock_spawner_can_fail_on_command() {
        let s = MockSpawner::new();
        s.fail_when_server_id("rust");
        // Can't `.unwrap_err()` directly because `Spawned` isn't `Debug`.
        match s.spawn("rust", Path::new("/tmp")).await {
            Ok(_) => panic!("expected spawn to fail"),
            Err(e) => assert!(e.to_string().contains("refused")),
        }
    }
}