scryer-cli 0.4.0

CLI tool and shared daemon runner for Scryer code intelligence
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
//! `scryer hook pre-grep`: answer a bare-identifier grep from the index (experimental, off by
//! default).
//!
//! Claude Code runs a `PreToolUse` hook before `Grep` and before Bash commands. When the agent
//! is about to grep for an identifier Scryer knows, the hook denies the call and puts Scryer's
//! caller answer in the reason, so the agent gets it in the same turn. Hooks cannot call MCP
//! tools, so the answer comes from the CLI.
//!
//! Guard rails: it intercepts only a bare identifier (at least four characters) that names
//! exactly one function or type, never a regex, string, path or non-identifier; each pattern is
//! denied at most once per session, so repeating the grep always runs it; it does nothing
//! unless `SCRYER_HOOK=on`, and `SCRYER_HOOK=off` is the kill switch.

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

use serde_json::Value;

/// What the hook does, from `SCRYER_HOOK`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Do nothing (the default, and `SCRYER_HOOK=off`).
    Off,
    /// Deny the grep and give Scryer's answer as the reason.
    On,
    /// Allow the grep and add Scryer's answer as context. A control for the experiment: it
    /// costs tokens and saves no turn.
    Context,
}

impl Mode {
    pub fn from_env() -> Self {
        Self::parse(std::env::var("SCRYER_HOOK").ok().as_deref())
    }

    pub fn parse(value: Option<&str>) -> Self {
        match value.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
            Some("on" | "1" | "true" | "deny") => Mode::On,
            Some("context") => Mode::Context,
            _ => Mode::Off,
        }
    }
}

/// A search the hook may answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GrepCall {
    pub pattern: String,
}

/// Four or more characters, a letter or underscore first, then letters, digits and underscores.
pub fn is_bare_identifier(pattern: &str) -> bool {
    let mut chars = pattern.chars();
    chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && pattern.len() >= 4
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Words in a path or glob that mean the agent is looking in docs or tests, where grep is the
/// right tool.
fn is_docs_or_tests(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    ["test", "doc", "bench", "example", "fixture"]
        .iter()
        .any(|w| lower.contains(w))
        || [".md", ".txt", ".json", ".yaml", ".yml", ".toml", ".lock"]
            .iter()
            .any(|ext| lower.contains(ext))
}

/// Whether `path` (relative to `cwd`) names a file rather than a directory to search.
fn is_one_file(cwd: &Path, path: &str) -> bool {
    cwd.join(path).is_file()
}

/// Split a shell command into words, or `None` when it uses anything beyond plain words and
/// quotes: pipes, redirects, substitution, globs, escapes.
fn shell_words(command: &str) -> Option<Vec<String>> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut in_word = false;
    let mut quote: Option<char> = None;
    for c in command.chars() {
        match quote {
            Some(q) if c == q => quote = None,
            Some('"') if matches!(c, '$' | '`' | '\\') => return None,
            Some(_) => current.push(c),
            None => match c {
                '\'' | '"' => {
                    quote = Some(c);
                    in_word = true;
                }
                c if c.is_whitespace() => {
                    if in_word {
                        words.push(std::mem::take(&mut current));
                        in_word = false;
                    }
                }
                '|' | '&' | ';' | '<' | '>' | '`' | '$' | '(' | ')' | '{' | '}' | '*' | '?'
                | '!' | '\\' | '~' | '#' => return None,
                c => {
                    current.push(c);
                    in_word = true;
                }
            },
        }
    }
    if quote.is_some() {
        return None;
    }
    if in_word {
        words.push(current);
    }
    Some(words)
}

/// The search a Bash command performs, if it is a plain `grep` or `rg` of one pattern.
fn bash_search(command: &str, cwd: &Path) -> Option<GrepCall> {
    let words = shell_words(command)?;
    let (program, rest) = words.split_first()?;
    if program != "grep" && program != "rg" {
        return None;
    }
    let mut positional = Vec::new();
    for word in rest {
        if let Some(long) = word.strip_prefix("--") {
            match long {
                "recursive" | "line-number" | "word-regexp" | "with-filename" | "no-messages" => {}
                l if l.starts_with("include=") || l.starts_with("exclude-dir=") => {
                    if is_docs_or_tests(l) {
                        return None;
                    }
                }
                _ => return None,
            }
        } else if let Some(short) = word.strip_prefix('-').filter(|s| !s.is_empty()) {
            // Flags that change what is matched or printed are not answered from the index.
            if !short.chars().all(|c| "rRnwHsI".contains(c)) {
                return None;
            }
        } else {
            positional.push(word.as_str());
        }
    }
    let (pattern, paths) = positional.split_first()?;
    if !is_bare_identifier(pattern) {
        return None;
    }
    for path in paths {
        if is_docs_or_tests(path) || is_one_file(cwd, path) {
            return None;
        }
    }
    Some(GrepCall {
        pattern: pattern.to_string(),
    })
}

/// The search a `Grep` tool call performs.
fn grep_tool_search(input: &Value, cwd: &Path) -> Option<GrepCall> {
    let flag = |key: &str| input.get(key).and_then(Value::as_bool).unwrap_or(false);
    // Case-insensitive and multiline searches are not an identifier lookup.
    if flag("-i") || flag("multiline") {
        return None;
    }
    let pattern = input.get("pattern")?.as_str()?;
    if !is_bare_identifier(pattern) {
        return None;
    }
    if let Some(path) = input.get("path").and_then(Value::as_str)
        && (is_docs_or_tests(path) || is_one_file(cwd, path))
    {
        return None;
    }
    for key in ["glob", "type"] {
        if let Some(value) = input.get(key).and_then(Value::as_str)
            && (is_docs_or_tests(value) || matches!(value, "md" | "json" | "yaml" | "toml" | "txt"))
        {
            return None;
        }
    }
    Some(GrepCall {
        pattern: pattern.to_string(),
    })
}

/// The search a `PreToolUse` event is about to run, if it is one the hook may answer.
pub fn classify(event: &Value) -> Option<GrepCall> {
    let cwd = event
        .get("cwd")
        .and_then(Value::as_str)
        .map_or_else(|| PathBuf::from("."), PathBuf::from);
    let input = event.get("tool_input")?;
    match event.get("tool_name")?.as_str()? {
        "Grep" => grep_tool_search(input, &cwd),
        "Bash" => bash_search(input.get("command")?.as_str()?, &cwd),
        _ => None,
    }
}

/// Whether an `inspect_symbol` answer names exactly one function or type of this project.
pub fn names_one_definition(inspected: &Value) -> bool {
    inspected["found"] == true
        && inspected.get("ambiguous").and_then(Value::as_bool) != Some(true)
        && inspected.get("is_external").and_then(Value::as_bool) != Some(true)
        && inspected["kind"].as_str().is_some_and(|kind| {
            matches!(
                kind,
                "fn" | "function"
                    | "method"
                    | "struct"
                    | "enum"
                    | "trait"
                    | "type"
                    | "class"
                    | "interface"
            )
        })
}

/// The hook's stdout that denies the call and gives `answer` as the reason.
pub fn deny_output(pattern: &str, answer: &str) -> String {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": format!(
                "Scryer answered this grep for `{pattern}` from its index, so it did not run:\n{answer}\nTo get the raw grep output, repeat the same search."
            ),
        }
    })
    .to_string()
}

/// The hook's stdout that lets the call run and adds `answer` as context.
pub fn context_output(pattern: &str, answer: &str) -> String {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "additionalContext": format!("Scryer's answer for `{pattern}` from its index:\n{answer}"),
        }
    })
    .to_string()
}

/// The patterns already answered in one session, so a repeat passes through.
pub struct SeenStore {
    path: PathBuf,
}

impl SeenStore {
    /// The store of `session_id`, in the runtime directory (or the temp directory).
    pub fn for_session(session_id: &str) -> Self {
        let dir = std::env::var_os("XDG_RUNTIME_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(std::env::temp_dir)
            .join("scryer");
        let safe: String = session_id
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                    c
                } else {
                    '_'
                }
            })
            .collect();
        Self {
            path: dir.join(format!("hook-{safe}.json")),
        }
    }

    #[cfg(test)]
    pub fn at(path: PathBuf) -> Self {
        Self { path }
    }

    fn patterns(&self) -> Vec<String> {
        std::fs::read_to_string(&self.path)
            .ok()
            .and_then(|text| serde_json::from_str(&text).ok())
            .unwrap_or_default()
    }

    pub fn seen(&self, pattern: &str) -> bool {
        self.patterns().iter().any(|p| p == pattern)
    }

    pub fn record(&self, pattern: &str) {
        let mut patterns = self.patterns();
        patterns.push(pattern.to_string());
        if let Some(parent) = self.path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let _ = std::fs::write(
            &self.path,
            serde_json::to_string(&patterns).unwrap_or_default(),
        );
    }
}

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

    fn grep(pattern: &str) -> Value {
        json!({"tool_name": "Grep", "tool_input": {"pattern": pattern}, "cwd": "/nonexistent"})
    }

    fn bash(command: &str) -> Value {
        json!({"tool_name": "Bash", "tool_input": {"command": command}, "cwd": "/nonexistent"})
    }

    fn pattern(event: &Value) -> Option<String> {
        classify(event).map(|c| c.pattern)
    }

    #[test]
    fn only_a_bare_identifier_of_four_or_more_characters_is_answered() {
        assert_eq!(
            pattern(&grep("index_project")).as_deref(),
            Some("index_project")
        );
        assert_eq!(pattern(&grep("Widget")).as_deref(), Some("Widget"));
        for not in [
            "foo",              // too short
            "foo.*bar",         // regex
            "fn index_project", // two words
            "index-project",
            "\"quoted\"",
            "src/main.rs",
            "9lives",
            "",
        ] {
            assert_eq!(pattern(&grep(not)), None, "{not}");
        }
    }

    #[test]
    fn a_search_narrowed_to_docs_tests_or_one_file_is_left_alone() {
        let with = |key: &str, value: Value| {
            json!({"tool_name": "Grep", "cwd": "/nonexistent",
                   "tool_input": {"pattern": "index_project", key: value}})
        };
        assert_eq!(pattern(&with("path", json!("docs/"))), None);
        assert_eq!(pattern(&with("path", json!("crates/x/tests"))), None);
        assert_eq!(pattern(&with("glob", json!("*.md"))), None);
        assert_eq!(pattern(&with("glob", json!("**/*_test.rs"))), None);
        assert_eq!(pattern(&with("type", json!("md"))), None);
        assert_eq!(pattern(&with("-i", json!(true))), None);
        assert_eq!(pattern(&with("multiline", json!(true))), None);
        // A code search over a directory or a code glob is answered.
        assert!(pattern(&with("path", json!("crates/"))).is_some());
        assert!(pattern(&with("glob", json!("*.rs"))).is_some());
        assert!(pattern(&with("type", json!("rust"))).is_some());
    }

    #[test]
    fn a_search_of_one_existing_file_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.rs"), "fn index_project() {}").unwrap();
        let event = json!({"tool_name": "Grep", "cwd": dir.path(),
                           "tool_input": {"pattern": "index_project", "path": "a.rs"}});
        assert_eq!(pattern(&event), None);
        let event = json!({"tool_name": "Bash", "cwd": dir.path(),
                           "tool_input": {"command": "grep -n index_project a.rs"}});
        assert_eq!(pattern(&event), None);
    }

    #[test]
    fn plain_grep_and_rg_commands_are_answered() {
        assert_eq!(
            pattern(&bash("grep -rn index_project .")).as_deref(),
            Some("index_project")
        );
        assert_eq!(
            pattern(&bash("rg index_project src")).as_deref(),
            Some("index_project")
        );
        assert_eq!(
            pattern(&bash("grep -rnw 'index_project' crates")).as_deref(),
            Some("index_project")
        );
        assert_eq!(
            pattern(&bash("grep -r --include=\"*.rs\" index_project .")).as_deref(),
            Some("index_project")
        );
    }

    #[test]
    fn anything_else_in_a_bash_command_is_never_intercepted() {
        for command in [
            "grep -rn index_project . | head",
            "grep -rn index_project . && ls",
            "grep -rn index_project . > out.txt",
            "grep -rn $NAME .",
            "grep -rn \"$(echo x)\" .",
            "grep -rn index_project *.rs",
            "grep -rni index_project .",   // case-insensitive
            "grep -rnl index_project .",   // lists files only
            "grep -rn -e index_project .", // explicit pattern flag
            "grep -rn 'index.*project' .",
            "grep -rn \"unterminated .",
            "cat index_project",
            "git grep index_project",
            "ls",
            "",
        ] {
            assert_eq!(pattern(&bash(command)), None, "{command}");
        }
    }

    #[test]
    fn other_tools_are_ignored() {
        let event = json!({"tool_name": "Read", "tool_input": {"file_path": "x.rs"}});
        assert_eq!(classify(&event), None);
    }

    #[test]
    fn the_mode_comes_from_the_environment_and_defaults_to_off() {
        assert_eq!(Mode::parse(None), Mode::Off);
        assert_eq!(Mode::parse(Some("")), Mode::Off);
        assert_eq!(Mode::parse(Some("off")), Mode::Off);
        assert_eq!(Mode::parse(Some("garbage")), Mode::Off);
        assert_eq!(Mode::parse(Some("on")), Mode::On);
        assert_eq!(Mode::parse(Some("ON")), Mode::On);
        assert_eq!(Mode::parse(Some("context")), Mode::Context);
    }

    #[test]
    fn exactly_one_function_or_type_qualifies() {
        assert!(names_one_definition(&json!({"found": true, "kind": "fn"})));
        assert!(names_one_definition(
            &json!({"found": true, "kind": "struct"})
        ));
        assert!(!names_one_definition(&json!({"found": false})));
        assert!(!names_one_definition(
            &json!({"found": true, "ambiguous": true, "kind": "fn"})
        ));
        assert!(!names_one_definition(
            &json!({"found": true, "kind": "const"})
        ));
        assert!(!names_one_definition(
            &json!({"found": true, "kind": "fn", "is_external": true})
        ));
    }

    #[test]
    fn a_pattern_is_denied_once_per_session() {
        let dir = tempfile::tempdir().unwrap();
        let store = SeenStore::at(dir.path().join("s/hook-a.json"));
        assert!(!store.seen("index_project"));
        store.record("index_project");
        assert!(store.seen("index_project"));
        assert!(!store.seen("other_name"));
    }

    #[test]
    fn the_deny_output_is_what_claude_code_expects() {
        let out: Value =
            serde_json::from_str(&deny_output("index_project", "callers: a, b")).unwrap();
        let specific = &out["hookSpecificOutput"];
        assert_eq!(specific["hookEventName"], "PreToolUse");
        assert_eq!(specific["permissionDecision"], "deny");
        let reason = specific["permissionDecisionReason"].as_str().unwrap();
        assert!(reason.contains("callers: a, b"));
        assert!(reason.contains("repeat the same search"));

        let out: Value = serde_json::from_str(&context_output("index_project", "x")).unwrap();
        assert!(
            out["hookSpecificOutput"]
                .get("permissionDecision")
                .is_none()
        );
        assert!(out["hookSpecificOutput"]["additionalContext"].is_string());
    }
}