reliary-agent 0.9.4

Grammar-free symbol intelligence — CLI and MCP server.
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
//! Shared harness for end-to-end tests.
//!
//! Spawns the real `reliary` binary as a subprocess and speaks line-delimited
//! JSON-RPC (MCP stdio transport) to it, exactly like Claude Code / OpenCode /
//! Pi do. No mocking: these tests exercise the shipped binary.
#![allow(dead_code)]

use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;

/// Absolute path to the built `reliary` binary.
pub fn binary_path() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_reliary"))
}

/// A minimal indexed project: a git repo with a couple of source files so
/// auto-trust fires and queries return deterministic results.
pub struct Fixture {
    pub dir: tempfile::TempDir,
}

impl Fixture {
    /// Create a git repo with `src/lib.rs` (defines `alpha`, calls `beta`)
    /// and `src/other.rs` (defines `beta`).
    pub fn new() -> Fixture {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();

        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(
            root.join("src/lib.rs"),
            r#"//! Fixture crate.
/// Alpha does a thing.
pub fn alpha() -> i32 {
    beta() + 1
}
"#,
        )
        .unwrap();
        std::fs::write(
            root.join("src/other.rs"),
            r#"/// Beta does another thing.
pub fn beta() -> i32 {
    41
}
"#,
        )
        .unwrap();

        // git repo marker (auto-trust looks for .git/). git is present on
        // GitHub runners and developer machines; skip cleanly if it is not.
        let ok = Command::new("git")
            .args(["init", "--quiet"])
            .current_dir(root)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        assert!(
            ok,
            "git init failed — the e2e tests require git on PATH (install git, or skip with --skip e2e_)"
        );

        Fixture { dir }
    }

    /// Build the index without starting an MCP server.
    /// A project whose types implement a trait both ways: one `#[derive]` and
    /// one manual `impl`. Used to check that a trait question answers with the
    /// implementing types rather than with a same-named method.
    pub fn trait_impls() -> Fixture {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(
            root.join("src/models.rs"),
            r#"#[derive(Debug, Clone, Default)]
pub struct Derived {
    pub id: i32,
}

pub struct Manual {
    pub id: i32,
}

impl Default for Manual {
    fn default() -> Self {
        Self { id: 0 }
    }
}

#[derive(Debug, Clone)]
pub struct NotDefault {
    pub id: i32,
}
"#,
        )
        .unwrap();
        let ok = Command::new("git")
            .args(["init", "--quiet"])
            .current_dir(root)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        if ok {
            for a in [["add", "-A"].as_slice(), ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "fixture"].as_slice()] {
                let _ = Command::new("git").args(a).current_dir(root)
                    .stdout(Stdio::null()).stderr(Stdio::null()).status();
            }
        }
        Fixture { dir }
    }

    /// A project with `n` functions that nothing calls, so a dead-code query
    /// returns a long list. Used to check that the output is capped.
    pub fn many_dead_functions(n: usize) -> Fixture {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        let mut body = String::from("pub fn live_entry() -> i32 {\n    1\n}\n\n");
        for i in 0..n {
            body.push_str(&format!("fn unused_helper_{i}() -> i32 {{\n    {i}\n}}\n\n"));
        }
        std::fs::write(root.join("src/lib.rs"), body).unwrap();
        let ok = Command::new("git")
            .args(["init", "--quiet"])
            .current_dir(root)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        if ok {
            for a in [["add", "-A"].as_slice(),
                      ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "fixture"].as_slice()] {
                let _ = Command::new("git").args(a).current_dir(root)
                    .stdout(Stdio::null()).stderr(Stdio::null()).status();
            }
        }
        Fixture { dir }
    }

    /// `pub_n` exported functions and `priv_n` private ones, none called.
    pub fn mixed_dead_functions(priv_n: usize, _unused: usize) -> Fixture {
        Self::mixed_dead_impl(priv_n)
    }

    fn mixed_dead_impl(pub_n: usize) -> Fixture {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        let mut body = String::from("pub fn live_entry() -> i32 {\n    1\n}\n\n");
        for i in 0..pub_n {
            body.push_str(&format!("pub fn pub_unused_{i}() -> i32 {{\n    {i}\n}}\n\n"));
        }
        for i in 0..12 {
            body.push_str(&format!("fn priv_unused_{i}() -> i32 {{\n    {i}\n}}\n\n"));
        }
        std::fs::write(root.join("src/lib.rs"), body).unwrap();
        let ok = Command::new("git").args(["init", "--quiet"]).current_dir(root)
            .stdout(Stdio::null()).stderr(Stdio::null())
            .status().map(|s| s.success()).unwrap_or(false);
        if ok {
            for a in [["add", "-A"].as_slice(),
                      ["-c","user.email=t@t","-c","user.name=t","commit","-qm","fixture"].as_slice()] {
                let _ = Command::new("git").args(a).current_dir(root)
                    .stdout(Stdio::null()).stderr(Stdio::null()).status();
            }
        }
        Fixture { dir }
    }

    pub fn trust(&self) {
        let mut cmd = Command::new(binary_path());
        cmd.args(["trust", "."])
            .current_dir(self.path())
            .env("NO_RELIARY_WATCHER", "1");
        let no_envs: &[(&str, &str)] = &[];
        apply_xdg_isolation(&mut cmd, self.path(), no_envs);
        let out = cmd.output().expect("run trust");
        assert!(
            out.status.success(),
            "trust failed: {}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            self.path().join(".reliary/index.sqlite").exists(),
            "trust did not create an index"
        );
    }

    pub fn path(&self) -> &Path {
        self.dir.path()
    }
}

/// Run the binary as a subprocess with a controlled environment.
///
/// XDG isolation: `init`/`doctor` honor `XDG_CONFIG_HOME` (and `dirs`
/// honors `XDG_DATA_HOME`), so a runner-exported XDG var would redirect
/// writes away from the fake HOME and every integration assertion would
/// read empty air. Both default to the fake home rooted at `cwd` unless
/// the caller passes them explicitly in `envs`.
pub fn apply_xdg_isolation(cmd: &mut Command, cwd: &Path, envs: &[(&str, &str)]) {
    let has = |k: &str| envs.iter().any(|(ek, _)| *ek == k);
    if !has("XDG_CONFIG_HOME") {
        cmd.env("XDG_CONFIG_HOME", cwd.join(".config"));
    }
    if !has("XDG_DATA_HOME") {
        cmd.env("XDG_DATA_HOME", cwd.join(".local/share"));
    }
}

/// Run the binary as a subprocess with a controlled environment.
pub fn run_cli(args: &[&str], cwd: &Path, envs: &[(&str, &str)]) -> std::process::Output {
    let mut cmd = Command::new(binary_path());
    cmd.args(args).current_dir(cwd);
    cmd.env("NO_RELIARY_WATCHER", "1");
    apply_xdg_isolation(&mut cmd, cwd, envs);
    for (k, v) in envs {
        cmd.env(k, v);
    }
    cmd.output().expect("spawn reliary")
}

/// Run the binary with explicit stdin (for interactive prompts).
pub fn run_cli_stdin(args: &[&str], cwd: &Path, envs: &[(&str, &str)], input: &str) -> std::process::Output {
    use std::io::Write;
    let mut cmd = Command::new(binary_path());
    cmd.args(args)
        .current_dir(cwd)
        .env("NO_RELIARY_WATCHER", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    apply_xdg_isolation(&mut cmd, cwd, envs);
    for (k, v) in envs {
        cmd.env(k, v);
    }
    let mut child = cmd.spawn().expect("spawn reliary");
    child
        .stdin
        .as_mut()
        .expect("stdin piped")
        .write_all(input.as_bytes())
        .expect("write stdin");
    child.wait_with_output().expect("wait reliary")
}

// ── MCP stdio client ──────────────────────────────────────────────────────

/// A live `reliary mcp` subprocess speaking JSON-RPC over stdio.
pub struct Mcp {
    child: Child,
    stdin: ChildStdin,
    /// Responses arrive on a channel from a reader thread, so tests can time
    /// out instead of hanging if the server stops responding.
    responses: Receiver<serde_json::Value>,
    _stdout_reader: std::thread::JoinHandle<()>,
    next_id: i64,
}

impl Mcp {
    /// Spawn `reliary mcp` inside `cwd`.
    ///
    /// `RELIARY_RESULT_CACHE=0` keeps every identical call a real call;
    /// `RELIARY_NO_TRUNCATE=1` keeps assertions on full output stable.
    pub fn start(cwd: &Path) -> Mcp {
        let mut cmd = Command::new(binary_path());
        cmd.arg("mcp")
            .current_dir(cwd)
            .env("NO_RELIARY_WATCHER", "1")
            .env("RELIARY_RESULT_CACHE", "0")
            .env("RELIARY_NO_TRUNCATE", "1")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null());
        // XDG isolation (same class as run_cli): the MCP server resolves the
        // index from CWD/roots, but auto-trust and config paths honor XDG.
        let no_envs: &[(&str, &str)] = &[];
        apply_xdg_isolation(&mut cmd, cwd, no_envs);
        let mut child = cmd.spawn().expect("spawn reliary mcp");

        let stdin = child.stdin.take().expect("child stdin");
        let stdout: ChildStdout = child.stdout.take().expect("child stdout");
        let (tx, rx) = mpsc::channel();

        let reader = std::thread::spawn(move || {
            let mut lines = BufReader::new(stdout).lines();
            while let Some(Ok(line)) = lines.next() {
                let line = line.trim();
                if line.is_empty() {
                    continue;
                }
                match serde_json::from_str::<serde_json::Value>(line) {
                    Ok(v) => {
                        if tx.send(v).is_err() {
                            break;
                        }
                    }
                    // Non-JSON line on stdout is a protocol violation, but the
                    // reader must not die — surface it as a sentinel so the
                    // test can assert rather than hang.
                    Err(_) => {
                        let _ = tx.send(serde_json::json!({ "__non_json__": line }));
                    }
                }
            }
        });

        Mcp { child, stdin, responses: rx, _stdout_reader: reader, next_id: 1 }
    }

    /// Send one JSON-RPC request and wait for its response.
    pub fn request(&mut self, method: &str, params: serde_json::Value) -> serde_json::Value {
        let id = self.next_id;
        self.next_id += 1;
        self.send_raw(&serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        }));
        self.read_response(Duration::from_secs(30))
    }

    /// Send raw bytes on stdin (for malformed-input tests).
    pub fn send_raw(&mut self, msg: &serde_json::Value) {
        let line = serde_json::to_string(msg).unwrap();
        self.send_line(&line);
    }

    /// Send an arbitrary line (no JSON validation).
    pub fn send_line(&mut self, line: &str) {
        writeln!(self.stdin, "{}", line).expect("write stdin");
        self.stdin.flush().expect("flush stdin");
    }

    /// Read the next message from stdout, or panic on timeout.
    pub fn read_response(&mut self, timeout: Duration) -> serde_json::Value {
        self.responses
            .recv_timeout(timeout)
            .unwrap_or_else(|_| panic!("timed out after {:?} waiting for MCP response", timeout))
    }

    /// Try to read a message, returning None on timeout (used by
    /// "server must stay silent" assertions).
    pub fn try_read_response(&mut self, timeout: Duration) -> Option<serde_json::Value> {
        self.responses.recv_timeout(timeout).ok()
    }

    pub fn initialize(&mut self) -> serde_json::Value {
        self.request(
            "initialize",
            serde_json::json!({ "protocolVersion": "2024-11-05" }),
        )
    }

    pub fn list_tools(&mut self) -> Vec<serde_json::Value> {
        let resp = self.request("tools/list", serde_json::json!({}));
        resp["result"]["tools"]
            .as_array()
            .unwrap_or_else(|| panic!("tools/list did not return an array: {}", resp))
            .clone()
    }

    /// Call a tool. Returns the raw JSON-RPC response.
    pub fn call_tool(&mut self, name: &str, args: serde_json::Value) -> serde_json::Value {
        self.request(
            "tools/call",
            serde_json::json!({ "name": name, "arguments": args }),
        )
    }

    /// Call a tool and return its concatenated text content.
    pub fn call_tool_text(&mut self, name: &str, args: serde_json::Value) -> String {
        let resp = self.call_tool(name, args);
        assert!(
            resp.get("error").is_none(),
            "tool {} returned an error: {}",
            name,
            resp
        );
        resp["result"]["content"]
            .as_array()
            .unwrap_or_else(|| panic!("tool {} returned no content array: {}", name, resp))
            .iter()
            .filter_map(|c| c.get("text").and_then(|t| t.as_str()))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Is the child still running?
    pub fn is_alive(&mut self) -> bool {
        matches!(self.child.try_wait(), Ok(None))
    }
}

impl Drop for Mcp {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}