Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

feat(cli): add opt-in Gemini CLI search hints (#2879)

Jarvis7bf7ac50e4df
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 191647c62..aa198f4ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the indexed folder and configured loopback node, with a per-session quota.
`--hooks --remove` preserves other hooks and session memory.
+- The same advisory search hints for Gemini CLI with `xerj init --hooks --host
+ gemini` on macOS/Linux (Refs #2642). It writes an `AfterTool` group to
+ `.gemini/settings.json`, because `BeforeTool` has no field that reaches the
+ model, and a millisecond `timeout` as that host expects. Matched tools are
+ `grep_search`, `search_file_content`, `glob` and `read_file`, anchored so MCP
+ tool names are not caught. Setup is refused when the host has hooks disabled.
+ Quotas, counters and backups are per host, and either host can be configured
+ or removed without touching the other.
+
- Opt-in Claude Code session handoff with `xerj init --memory` on macOS/Linux
(Refs #2645). SessionEnd queues a background redacting import and lexical
autoindex; SessionStart returns bounded, cited historical excerpts from a
diff --git a/docs/RERANK.md b/docs/RERANK.md
index 3a2c602d3..6a0d8997d 100644
--- a/docs/RERANK.md
+++ b/docs/RERANK.md
@@ -413,8 +413,8 @@ the picture:
Runtime authentication is sent only to that loopback node.
`xerj init hook` (installed only by `xerj init --hooks`) reads bounded catalog
run metadata from its configured loopback node with runtime authentication.
- Tool inputs, patterns and session IDs are never sent. Proxies and redirects
- are disabled. It adds no node-side egress.
+ Tool inputs, patterns, tool results and session IDs are never sent. Proxies
+ and redirects are disabled. It adds no node-side egress.
`xerj feedback --open-pr` runs your `gh` to open a GitHub pull request with
the report it drafted; without that flag it does nothing over the network.
diff --git a/docs/recipes/air-gapped-deployment.md b/docs/recipes/air-gapped-deployment.md
index f866eb8ee..dea07c858 100644
--- a/docs/recipes/air-gapped-deployment.md
+++ b/docs/recipes/air-gapped-deployment.md
@@ -48,7 +48,7 @@ those two files before entering the enclave.
| Cluster | Disabled | Single-node startup does not initialize the Raft transport |
| REST / ES-compatible listeners | `127.0.0.1` | The default is loopback-only |
| `xerj sessions hook` (opt-in `xerj init --memory`) | Off until installed | Sends redacted session exports/excerpts and runtime auth to the configured loopback node, reads memories back; remote URLs, redirects and proxies are refused. No external service or model is required |
-| `xerj init hook` (opt-in `xerj init --hooks`) | Off until installed | Reads catalog run metadata using runtime auth from the configured loopback node; no tool input, query or session ID is sent. Proxies and redirects are disabled |
+| `xerj init hook` (opt-in `xerj init --hooks`, either host) | Off until installed | Reads catalog run metadata using runtime auth from the configured loopback node; no tool input, query, tool result or session ID is sent. Proxies and redirects are disabled |
| `autoindex` and MCP clients | Localhost defaults | They connect to `localhost`; they do not create a public listener |
| Runtime telemetry/update/license activation | None | No outbound call is made by the running binary for these purposes |
diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rs
index d0e75cb38..bc099cec8 100644
--- a/engine/crates/xerj-autoindex/src/init.rs
+++ b/engine/crates/xerj-autoindex/src/init.rs
@@ -65,7 +65,8 @@ OPTIONS:
(default $XERJ_URL or http://localhost:9200)
--dry-run print what would be written, write nothing
--memory opt in to project-local Claude Code session handoff (macOS/Linux)
- --hooks opt in to advisory Claude Code search hints (macOS/Linux)
+ --hooks opt in to advisory search hints (macOS/Linux)
+ --host <HOST> with --hooks: claude (default) or gemini
--remove with --memory or --hooks, remove only that feature; keep data
--disable-feedback
accepted; turns off the feedback invitation on help
@@ -84,7 +85,12 @@ Grep/Glob or the third Read can suggest a project-scoped search when the loopbac
node catalog confirms this exact folder was indexed. At most one hint per ten
matching calls per session (up to 64 sessions retained); no tool is blocked or
rewritten. Private counters/backups live in .claude/xerj-hints/. Configure/remove
---memory and --hooks separately. See tools/search-hints/README.md.
+--memory and --hooks separately.
+With --hooks --host gemini, use .gemini/settings.json and .gemini/xerj-hints/.
+Gemini's AfterTool appends a hint after grep_search/search_file_content, glob or
+the third read_file; BeforeTool cannot deliver advisory context to the model.
+Remove with --hooks --host gemini --remove. Neither host's setup changes the
+other. Restart the selected host after setup. See tools/search-hints/README.md.
After ordinary init: restart the agent session so it picks up the new tools, then
`xerj autoindex <folder> --prefix <name>` anything you want searchable.
@@ -126,7 +132,7 @@ fn agents_md_section() -> String {
Index each repo under its own prefix: `xerj autoindex <folder> --prefix <name>`, then\n\
pass the same `--prefix <name>` to `xerj search` and `xerj def` (without it they search\n\
the default `ax` prefix). Cite file:line for anything you rely on.\n\
- Optional Claude Code search reminders: `xerj init --hooks`; disable with `xerj init --hooks --remove`.\n\n\
+ Optional search reminders: `xerj init --hooks` for Claude Code; add `--host gemini` for Gemini CLI (after-tool hints). Add `--remove` with the same host to disable.\n\n\
To find an installed skill by task, run `xerj autoindex --skills` once (it indexes\n\
each skill folder it finds: `.claude/skills` in the home directory and in this\n\
project, `.codex/skills`, `.agents/skills`), then\n\
@@ -593,6 +599,7 @@ struct InitFlags {
help: bool,
memory: bool,
hooks: bool,
+ host: Option<crate::search_hints::Host>,
remove: bool,
}
@@ -605,6 +612,7 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
let mut dry = false;
let mut memory = false;
let mut hooks = false;
+ let mut host = None;
let mut remove = false;
let mut it = args.into_iter();
while let Some(a) = it.next() {
@@ -616,6 +624,7 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
help: true,
memory,
hooks,
+ host,
remove,
});
}
@@ -623,6 +632,18 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
"--dry-run" => dry = true,
"--memory" => memory = true,
"--hooks" => hooks = true,
+ "--host" => {
+ if host.is_some() {
+ return Err("xerj init: --host may be specified only once".into());
+ }
+ let value = it
+ .next()
+ .ok_or("xerj init: --host requires claude or gemini")?;
+ host = Some(
+ crate::search_hints::Host::parse(&value)
+ .map_err(|e| format!("xerj init: {e}"))?,
+ );
+ }
"--remove" => remove = true,
// Also stripped by args_after_subcommand. Accepted here so a
// caller that passes the raw list still does not exit 2.
@@ -636,18 +657,42 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
if memory && hooks {
return Err("xerj init: configure --memory and --hooks separately".into());
}
+ if host.is_some() && !hooks {
+ return Err("xerj init: --host requires --hooks".into());
+ }
Ok(InitFlags {
url,
dry,
help: false,
memory,
hooks,
+ host,
remove,
})
}
#[cfg(test)]
mod memory_flag_regression {
+ #[test]
+ fn gemini_search_hints_require_explicit_host_and_hooks() {
+ assert!(
+ super::read_init_flags(["--hooks", "--host", "gemini", "--dry-run"].map(String::from))
+ .is_ok(),
+ "Gemini search hints must accept an explicit host"
+ );
+ assert!(super::read_init_flags(
+ ["--hooks", "--host", "gemini", "--remove"].map(String::from)
+ )
+ .is_ok());
+ for args in [
+ vec!["--host", "gemini"],
+ vec!["--memory", "--host", "gemini"],
+ vec!["--hooks", "--host", "unknown"],
+ vec!["--hooks", "--host"],
+ ] {
+ assert!(super::read_init_flags(args.into_iter().map(String::from)).is_err());
+ }
+ }
#[test]
fn search_hints_are_an_explicit_separate_opt_in() {
assert!(super::read_init_flags(["--hooks", "--dry-run"].map(String::from)).is_ok());
@@ -688,7 +733,14 @@ pub fn run_init_cli() -> i32 {
.map_err(anyhow::Error::from)
.and_then(|binary| {
if flags.hooks {
- crate::search_hints::configure(&cwd, &url, dry, flags.remove, &binary)
+ crate::search_hints::configure(
+ flags.host.unwrap_or_default(),
+ &cwd,
+ &url,
+ dry,
+ flags.remove,
+ &binary,
+ )
} else {
crate::session_memory::configure(&cwd, &url, dry, flags.remove, &binary)
}
diff --git a/engine/crates/xerj-autoindex/src/search_hints.rs b/engine/crates/xerj-autoindex/src/search_hints.rs
index 9c490b022..8cf309c45 100644
--- a/engine/crates/xerj-autoindex/src/search_hints.rs
+++ b/engine/crates/xerj-autoindex/src/search_hints.rs
@@ -1,5 +1,6 @@
-//! Opt-in, advisory-only Claude Code PreToolUse hints (#2642).
+//! Opt-in, advisory-only Claude Code PreToolUse / Gemini CLI AfterTool hints (#2642).
//! Host contract: https://code.claude.com/docs/en/hooks#pretooluse-decision-control.
+//! Gemini: https://geminicli.com/docs/hooks/reference/#aftertool (milliseconds).
//! Return additionalContext only: never permissionDecision, updatedInput or exit 2.
use anyhow::{ensure, Context, Result};
use serde::{Deserialize, Serialize};
@@ -11,8 +12,67 @@ use std::time::Duration;
// Reuse the session hook's bounded, no-symlink, private/atomic file operations.
use crate::session_memory::{atomic, digest, encode, lock, loopback, private_dir, quote, read};
-const DIRECTORY: &str = ".claude/xerj-hints";
-const SETTINGS: &str = ".claude/settings.json";
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) enum Host {
+ #[default]
+ Claude,
+ Gemini,
+}
+
+impl Host {
+ pub(crate) fn parse(value: &str) -> Result<Self> {
+ match value {
+ "claude" => Ok(Self::Claude),
+ "gemini" => Ok(Self::Gemini),
+ _ => anyhow::bail!("unknown search hint host '{value}'; use claude or gemini"),
+ }
+ }
+ const fn directory(self) -> &'static str {
+ match self {
+ Self::Claude => ".claude/xerj-hints",
+ Self::Gemini => ".gemini/xerj-hints",
+ }
+ }
+ const fn settings(self) -> &'static str {
+ match self {
+ Self::Claude => ".claude/settings.json",
+ Self::Gemini => ".gemini/settings.json",
+ }
+ }
+ fn event(self) -> &'static str {
+ match self {
+ Self::Claude => "PreToolUse",
+ Self::Gemini => "AfterTool",
+ }
+ }
+ fn label(self) -> &'static str {
+ match self {
+ Self::Claude => "Claude Code",
+ Self::Gemini => "Gemini CLI",
+ }
+ }
+ fn flag(self) -> &'static str {
+ match self {
+ Self::Claude => "",
+ Self::Gemini => " --host gemini",
+ }
+ }
+ fn tool(self, name: &str) -> Option<&'static str> {
+ match (self, name) {
+ (Self::Claude, "Read") | (Self::Gemini, "read_file") => Some("Read"),
+ (Self::Claude, "Grep") | (Self::Gemini, "grep_search" | "search_file_content") => {
+ Some("Grep")
+ }
+ (Self::Claude, "Glob") | (Self::Gemini, "glob") => Some("Glob"),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+const DIRECTORY: &str = Host::Claude.directory();
+#[cfg(test)]
+const SETTINGS: &str = Host::Claude.settings();
const LIMIT: u64 = 64 * 1024;
const INTERVAL: u64 = 10;
const MAX_SESSIONS: usize = 64;
@@ -26,37 +86,44 @@ struct Config {
group: Value,
}
-fn group(project: &Path, binary: &Path) -> Result<Value> {
+fn group(host: Host, project: &Path, binary: &Path) -> Result<Value> {
let project = project.to_str().context("project path must be UTF-8")?;
let binary = binary.to_str().context("binary path must be UTF-8")?;
ensure!(
!project.chars().chain(binary.chars()).any(char::is_control),
"control characters in hook paths"
);
- Ok(json!({"matcher":"Grep|Glob|Read", "hooks":[{
- "type":"command", "command":format!("{} init hook --project {}", quote(binary), quote(project)),
- "timeout":2
+ let (matcher, timeout) = match host {
+ Host::Claude => ("Grep|Glob|Read", 2),
+ // Gemini regex matchers are unanchored by default. Do not match MCP tools.
+ Host::Gemini => ("^(grep_search|search_file_content|glob|read_file)$", 2000),
+ };
+ Ok(json!({"matcher":matcher, "hooks":[{
+ "type":"command", "command":format!("{} init hook --project {}{}", quote(binary), quote(project), host.flag()),
+ "timeout":timeout
}]}))
}
pub(crate) fn configure(
+ host: Host,
project: &Path,
url: &str,
dry: bool,
remove: bool,
binary: &Path,
) -> Result<Vec<String>> {
- configure_with(project, url, dry, remove, binary, atomic)
+ configure_with(host, project, url, (dry, remove), binary, atomic)
}
fn configure_with(
+ host: Host,
project: &Path,
url: &str,
- dry: bool,
- remove: bool,
+ action: (bool, bool),
binary: &Path,
publish_settings: impl FnOnce(&Path, &[u8]) -> Result<()>,
) -> Result<Vec<String>> {
+ let (dry, remove) = action;
ensure!(
cfg!(unix),
"search hint hooks currently support macOS and Linux only"
@@ -64,9 +131,9 @@ fn configure_with(
let project = project.canonicalize()?;
loopback(url)?;
let url = reqwest::Url::parse(url)?.to_string();
- let dir = project.join(DIRECTORY);
+ let dir = project.join(host.directory());
let config_path = dir.join("config.json");
- let path = project.join(SETTINGS);
+ let path = project.join(host.settings());
let old = read(&path, 1024 * 1024)?;
let old_config = read(&config_path, LIMIT)?;
let previous: Option<Config> = old_config
@@ -86,25 +153,30 @@ fn configure_with(
.unwrap_or(json!({}));
ensure!(
settings.is_object(),
- "Claude settings must be an object; not touching it"
+ "{} settings must be an object; not touching it",
+ host.label()
);
+ if host == Host::Gemini && !remove {
+ ensure!(settings.pointer("/hooksConfig/enabled") != Some(&json!(false)),
+ "Gemini hooks are disabled in this project's settings; enable hooksConfig.enabled before installing search hints");
+ }
if remove && previous.as_ref().is_none_or(|p| !p.enabled) {
return Ok(vec![
"search hints already disabled; backups and counters kept".into(),
]);
}
- let wanted = group(&project, binary)?;
+ let wanted = group(host, &project, binary)?;
let root = settings.as_object_mut().expect("checked object");
let hooks = root
.entry("hooks")
.or_insert(json!({}))
.as_object_mut()
- .context("Claude hooks must be an object")?;
+ .context("hooks must be an object")?;
let groups = hooks
- .entry("PreToolUse")
+ .entry(host.event())
.or_insert(json!([]))
.as_array_mut()
- .context("PreToolUse must be an array")?;
+ .with_context(|| format!("{} must be an array", host.event()))?;
let owned = previous.as_ref().filter(|p| p.enabled);
if let Some(p) = owned {
ensure!(groups.iter().filter(|g| *g == &p.group).count() == 1,
@@ -122,7 +194,7 @@ fn configure_with(
groups.push(wanted.clone());
}
if groups.is_empty() {
- hooks.remove("PreToolUse");
+ hooks.remove(host.event());
}
if hooks.is_empty() {
root.remove("hooks");
@@ -140,13 +212,28 @@ fn configure_with(
bytes.len() <= 1024 * 1024 && config_bytes.len() as u64 <= LIMIT,
"search hint configuration exceeds its read budget; not touching settings"
);
- let lines = vec![format!("{} Claude Code search hints (Grep/Glob/repeated Read; loopback only)",
- match (dry, remove) { (true,true)=>"would disable", (true,false)=>"would configure", (false,true)=>"disabled", (false,false)=>"enabled" }),
- "Use xerj init --hooks --remove to disable; private backups/counters remain in .claude/xerj-hints/".into()];
+ let lines = vec![
+ format!(
+ "{} {} search hints ({}; loopback only)",
+ match (dry, remove) {
+ (true, true) => "would disable",
+ (true, false) => "would configure",
+ (false, true) => "disabled",
+ (false, false) => "enabled",
+ },
+ host.label(),
+ host.event()
+ ),
+ format!(
+ "Use xerj init --hooks{} --remove to disable; private backups/counters remain in {}/",
+ host.flag(),
+ host.directory()
+ ),
+ ];
if dry {
return Ok(lines);
}
- fs::create_dir_all(project.join(".claude"))?;
+ fs::create_dir_all(path.parent().context("missing settings parent")?)?;
private_dir(&dir)?;
let _lease = lock(&dir.join("state.lock"))?;
// Serialise installers and runtime counters; refuse a stale preflight.
@@ -333,10 +420,11 @@ fn probe(config: &Config) -> Result<Option<String>> {
))
}
-fn handle(project: &Path, input: &[u8]) -> Result<Option<Value>> {
- handle_with(project, input, probe)
+fn handle(host: Host, project: &Path, input: &[u8]) -> Result<Option<Value>> {
+ handle_with(host, project, input, probe)
}
fn handle_with(
+ host: Host,
project: &Path,
input: &[u8],
probe: impl FnOnce(&Config) -> Result<Option<String>>,
@@ -346,9 +434,10 @@ fn handle_with(
"unsupported hook or oversized input"
);
let event: Value = serde_json::from_slice(input)?;
- ensure!(event["hook_event_name"] == "PreToolUse", "wrong event");
- let tool = event["tool_name"].as_str().context("missing tool")?;
- ensure!(matches!(tool, "Grep" | "Glob" | "Read"), "unmatched tool");
+ ensure!(event["hook_event_name"] == host.event(), "wrong event");
+ let tool = host
+ .tool(event["tool_name"].as_str().context("missing tool")?)
+ .context("unmatched tool")?;
let sid = event["session_id"]
.as_str()
.filter(|s| !s.is_empty() && s.len() <= 256)
@@ -356,7 +445,7 @@ fn handle_with(
let project = project.canonicalize()?;
let cwd = Path::new(event["cwd"].as_str().context("missing cwd")?).canonicalize()?;
ensure!(cwd == project, "different working directory");
- let dir = project.join(DIRECTORY);
+ let dir = project.join(host.directory());
let config: Config =
serde_json::from_slice(&read(&dir.join("config.json"), LIMIT)?.context("not configured")?)?;
ensure!(
@@ -392,7 +481,7 @@ fn handle_with(
);
let output = prefix.map(|prefix| {
session.last_hint = Some(session.calls);
- json!({"hookSpecificOutput":{"hookEventName":"PreToolUse", "additionalContext":format!(
+ json!({"hookSpecificOutput":{"hookEventName":host.event(), "additionalContext":format!(
"This folder has an indexed XERJ corpus: try `xerj search --prefix {prefix} --url {endpoint} \"<words>\"` or `xerj def --prefix {prefix} --url {endpoint} \"<symbol>\"` for cited passages.")}})
});
atomic(&path, &encode(&counters)?)?;
@@ -404,12 +493,18 @@ fn handle_with(
pub fn run(args: &[String]) -> i32 {
let result = (|| -> Result<Option<Value>> {
ensure!(
- args.len() == 2 && args[0] == "--project",
+ matches!(args.len(), 2 | 4) && args[0] == "--project",
"invalid arguments"
);
+ let host = if args.len() == 4 {
+ ensure!(args[2] == "--host", "invalid host argument");
+ Host::parse(&args[3])?
+ } else {
+ Host::Claude
+ };
let mut bytes = Vec::new();
std::io::stdin().take(LIMIT + 1).read_to_end(&mut bytes)?;
- handle(Path::new(&args[1]), &bytes)
+ handle(host, Path::new(&args[1]), &bytes)
})();
if let Ok(Some(value)) = result {
use std::io::Write;
diff --git a/engine/crates/xerj-autoindex/src/search_hints/tests.rs b/engine/crates/xerj-autoindex/src/search_hints/tests.rs
index 920c904f2..8507e66ac 100644
--- a/engine/crates/xerj-autoindex/src/search_hints/tests.rs
+++ b/engine/crates/xerj-autoindex/src/search_hints/tests.rs
@@ -4,6 +4,7 @@ fn project() -> tempfile::TempDir {
}
fn install(p: &Path, dry: bool, remove: bool) -> Result<Vec<String>> {
configure(
+ Host::Claude,
p,
"http://127.0.0.1:9200",
dry,
@@ -15,7 +16,10 @@ fn event(p: &Path, sid: &str, tool: &str) -> Vec<u8> {
serde_json::to_vec(&json!({"hook_event_name":"PreToolUse","cwd":p.canonicalize().unwrap(), "session_id":sid,"tool_name":tool,"tool_input":{"pattern":"do not send or persist"}})).unwrap()
}
fn fire(p: &Path, sid: &str, tool: &str) -> Option<Value> {
- handle_with(p, &event(p, sid, tool), |_| Ok(Some("my-repo".into()))).unwrap()
+ handle_with(Host::Claude, p, &event(p, sid, tool), |_| {
+ Ok(Some("my-repo".into()))
+ })
+ .unwrap()
}
#[test]
fn dry_run_merge_reconfigure_remove_and_memory_coexistence() {
@@ -46,6 +50,7 @@ fn dry_run_merge_reconfigure_remove_and_memory_coexistence() {
.unwrap();
assert!(cmd.contains("'\\''"));
configure(
+ Host::Claude,
p.path(),
"http://127.0.0.1:9201",
false,
@@ -81,7 +86,7 @@ fn dry_run_merge_reconfigure_remove_and_memory_coexistence() {
assert!(fire_after_removal(p.path()).is_err());
}
fn fire_after_removal(p: &Path) -> Result<Option<Value>> {
- handle_with(p, &event(p, "x", "Grep"), |_| {
+ handle_with(Host::Claude, p, &event(p, "x", "Grep"), |_| {
panic!("disabled hook contacted node")
})
}
@@ -133,6 +138,7 @@ fn malformed_edited_duplicated_and_foreign_configuration_refuse_without_overwrit
let p = project();
fs::create_dir(p.path().join(".claude")).unwrap();
let wanted = group(
+ Host::Claude,
&p.path().canonicalize().unwrap(),
Path::new("/opt/xerj's bin/xerj"),
)
@@ -184,37 +190,43 @@ fn bounded_sessions_and_counters_busy_or_corrupt_abstain() {
install(p.path(), false, false).unwrap();
let dir = p.path().join(DIRECTORY);
let lease = lock(&dir.join("state.lock")).unwrap();
- assert!(
- handle_with(p.path(), &event(p.path(), "x", "Grep"), |_| panic!(
- "busy probe"
- ))
- .is_err()
- );
+ assert!(handle_with(
+ Host::Claude,
+ p.path(),
+ &event(p.path(), "x", "Grep"),
+ |_| panic!("busy probe")
+ )
+ .is_err());
drop(lease);
fs::write(dir.join("counters.json"), b"{bad").unwrap();
- assert!(
- handle_with(p.path(), &event(p.path(), "x", "Grep"), |_| panic!(
- "corrupt probe"
- ))
- .is_err()
- );
+ assert!(handle_with(
+ Host::Claude,
+ p.path(),
+ &event(p.path(), "x", "Grep"),
+ |_| panic!("corrupt probe")
+ )
+ .is_err());
}
#[test]
fn offline_and_unindexed_calls_are_silent_and_do_not_consume_hint_slot() {
let p = project();
install(p.path(), false, false).unwrap();
let e = event(p.path(), "x", "Grep");
- assert!(handle_with(p.path(), &e, |_| anyhow::bail!("offline"))
+ assert!(
+ handle_with(Host::Claude, p.path(), &e, |_| anyhow::bail!("offline"))
+ .unwrap()
+ .is_none()
+ );
+ assert!(handle_with(Host::Claude, p.path(), &e, |_| Ok(None))
.unwrap()
.is_none());
- assert!(handle_with(p.path(), &e, |_| Ok(None)).unwrap().is_none());
assert!(fire(p.path(), "x", "Grep").is_some());
for bad in [
b"invalid".as_slice(),
b"{}",
&vec![b'x'; LIMIT as usize + 1],
] {
- assert!(handle_with(p.path(), bad, |_| panic!("invalid probe")).is_err());
+ assert!(handle_with(Host::Claude, p.path(), bad, |_| panic!("invalid probe")).is_err());
}
let mut e: Value = serde_json::from_slice(&e).unwrap();
for (field, value) in [
@@ -225,12 +237,13 @@ fn offline_and_unindexed_calls_are_silent_and_do_not_consume_hint_slot() {
] {
let old = e[field].clone();
e[field] = value;
- assert!(
- handle_with(p.path(), &serde_json::to_vec(&e).unwrap(), |_| panic!(
- "mismatched probe"
- ))
- .is_err()
- );
+ assert!(handle_with(
+ Host::Claude,
+ p.path(),
+ &serde_json::to_vec(&e).unwrap(),
+ |_| panic!("mismatched probe")
+ )
+ .is_err());
e[field] = old;
}
}
@@ -292,7 +305,15 @@ fn remote_urls_and_symlinks_refuse_before_settings_changes() {
"http://user:[email protected]:9200",
"http://127.0.0.1:9200/?key=x",
] {
- assert!(configure(p.path(), url, false, false, Path::new("/bin/xerj")).is_err());
+ assert!(configure(
+ Host::Claude,
+ p.path(),
+ url,
+ false,
+ false,
+ Path::new("/bin/xerj")
+ )
+ .is_err());
assert_eq!(fs::read_dir(p.path()).unwrap().count(), 0);
}
#[cfg(unix)]
@@ -388,10 +409,10 @@ fn failed_settings_publication_rolls_back_config_and_allows_retry() {
let settings = fs::read(p.path().join(SETTINGS)).unwrap();
let config = fs::read(p.path().join(DIRECTORY).join("config.json")).unwrap();
let error = configure_with(
+ Host::Claude,
p.path(),
"http://127.0.0.1:9200",
- false,
- true,
+ (false, true),
Path::new("/bin/xerj"),
|_, _| anyhow::bail!("injected publication failure"),
)
@@ -419,3 +440,220 @@ fn installing_into_near_limit_settings_refuses_before_creating_unreadable_state(
assert_eq!(fs::read(p.path().join(SETTINGS)).unwrap(), before);
assert!(!p.path().join(DIRECTORY).exists());
}
+
+fn gemini_event(p: &Path, sid: &str, tool: &str) -> Vec<u8> {
+ serde_json::to_vec(
+ &json!({"hook_event_name":"AfterTool", "cwd":p.canonicalize().unwrap(),
+ "session_id":sid, "tool_name":tool, "tool_input":{"pattern":"PRIVATE_INPUT"},
+ "tool_response":{"llmContent":"PRIVATE_RESULT"}}),
+ )
+ .unwrap()
+}
+fn gemini_install(p: &Path, dry: bool, remove: bool) -> Result<Vec<String>> {
+ configure(
+ Host::Gemini,
+ p,
+ "http://127.0.0.1:9200",
+ dry,
+ remove,
+ Path::new("/opt/xerj's bin/xerj"),
+ )
+}
+#[test]
+fn gemini_install_uses_after_tool_and_milliseconds_and_preserves_both_hosts() {
+ let p = project();
+ gemini_install(p.path(), true, false).unwrap();
+ assert_eq!(fs::read_dir(p.path()).unwrap().count(), 0);
+ install(p.path(), false, false).unwrap();
+ let claude = fs::read(p.path().join(SETTINGS)).unwrap();
+ fs::create_dir(p.path().join(".gemini")).unwrap();
+ let settings = p.path().join(Host::Gemini.settings());
+ let dir = p.path().join(Host::Gemini.directory());
+ let original = json!({"mcpServers":{"other":{"command":"other"}},"hooks":{
+ "BeforeTool":[{"matcher":".*","hooks":[]}],
+ "AfterTool":[{"matcher":"read_file","hooks":[]}]}});
+ let original_bytes = encode(&original).unwrap();
+ fs::write(&settings, &original_bytes).unwrap();
+ gemini_install(p.path(), false, false).unwrap();
+ let first = fs::read(&settings).unwrap();
+ gemini_install(p.path(), false, false).unwrap();
+ assert_eq!(first, fs::read(&settings).unwrap());
+ let value: Value = serde_json::from_slice(&first).unwrap();
+ assert_eq!(
+ value["hooks"]["BeforeTool"],
+ original["hooks"]["BeforeTool"]
+ );
+ let group = &value["hooks"]["AfterTool"][1];
+ assert_eq!(group["hooks"][0]["timeout"], 2000);
+ let matcher = regex::Regex::new(group["matcher"].as_str().unwrap()).unwrap();
+ for name in ["grep_search", "search_file_content", "glob", "read_file"] {
+ assert!(matcher.is_match(name));
+ }
+ for name in [
+ "mcp_other_grep_search",
+ "read_file_extra",
+ "read_many_files",
+ "run_shell_command",
+ ] {
+ assert!(!matcher.is_match(name));
+ }
+ let cmd = group["hooks"][0]["command"].as_str().unwrap();
+ assert!(cmd.ends_with(" --host gemini") && cmd.contains("'\\''"));
+ assert_eq!(fs::read(p.path().join(SETTINGS)).unwrap(), claude);
+ assert!(fs::read_dir(&dir)
+ .unwrap()
+ .any(|f| fs::read(f.unwrap().path()).ok().as_deref() == Some(original_bytes.as_slice())));
+ configure(
+ Host::Gemini,
+ p.path(),
+ "http://127.0.0.1:9201",
+ false,
+ false,
+ Path::new("/new/xerj"),
+ )
+ .unwrap();
+ let updated: Value = serde_json::from_slice(&fs::read(&settings).unwrap()).unwrap();
+ assert_eq!(updated["hooks"]["AfterTool"].as_array().unwrap().len(), 2);
+ assert!(updated["hooks"]["AfterTool"][1]["hooks"][0]["command"]
+ .as_str()
+ .unwrap()
+ .contains("/new/xerj"));
+ gemini_install(p.path(), false, true).unwrap();
+ gemini_install(p.path(), false, true).unwrap();
+ assert_eq!(
+ serde_json::from_slice::<Value>(&fs::read(&settings).unwrap()).unwrap(),
+ original
+ );
+ assert_eq!(fs::read(p.path().join(SETTINGS)).unwrap(), claude);
+ assert!(fire(p.path(), "still-enabled", "Grep").is_some());
+ assert!(handle_with(
+ Host::Gemini,
+ p.path(),
+ &gemini_event(p.path(), "disabled", "glob"),
+ |_| panic!("disabled probe")
+ )
+ .is_err());
+}
+
+#[test]
+fn gemini_advisory_quota_and_read_threshold_are_host_and_session_local() {
+ let p = project();
+ install(p.path(), false, false).unwrap();
+ gemini_install(p.path(), false, false).unwrap();
+ let fire_gemini = |sid, tool| {
+ handle_with(
+ Host::Gemini,
+ p.path(),
+ &gemini_event(p.path(), sid, tool),
+ |_| Ok(Some("gemini-repo".into())),
+ )
+ .unwrap()
+ };
+ assert!(fire_gemini("same-session", "read_file").is_none());
+ assert!(fire_gemini("same-session", "read_file").is_none());
+ let value = fire_gemini("same-session", "read_file").unwrap();
+ assert_eq!(value.as_object().unwrap().len(), 1);
+ assert_eq!(value["hookSpecificOutput"].as_object().unwrap().len(), 2);
+ assert_eq!(value["hookSpecificOutput"]["hookEventName"], "AfterTool");
+ let hint = value["hookSpecificOutput"]["additionalContext"]
+ .as_str()
+ .unwrap();
+ assert!(hint.contains("--prefix gemini-repo --url 'http://127.0.0.1:9200'"));
+ for _ in 0..9 {
+ assert!(fire_gemini("same-session", "grep_search").is_none());
+ }
+ assert!(fire_gemini("same-session", "glob").is_some());
+ assert!(fire(p.path(), "same-session", "Grep").is_some());
+ assert!(fire_gemini("other-session", "search_file_content").is_some());
+ let e = gemini_event(p.path(), "offline", "grep_search");
+ assert!(
+ handle_with(Host::Gemini, p.path(), &e, |_| anyhow::bail!("offline"))
+ .unwrap()
+ .is_none()
+ );
+ assert!(fire_gemini("offline", "grep_search").is_some());
+ let dir = p.path().join(Host::Gemini.directory());
+ let counters = fs::read_to_string(dir.join("counters.json")).unwrap();
+ for private in ["PRIVATE_INPUT", "PRIVATE_RESULT", "same-session"] {
+ assert!(!counters.contains(private));
+ }
+ let before = counters.into_bytes();
+ for (field, v) in [
+ ("tool_name", json!("Grep")),
+ ("tool_name", json!("mcp_other_grep_search")),
+ ("hook_event_name", json!("BeforeTool")),
+ ("hook_event_name", json!("PreToolUse")),
+ ("cwd", json!("/")),
+ ] {
+ let mut bad: Value = serde_json::from_slice(&e).unwrap();
+ bad[field] = v;
+ assert!(
+ handle_with(Host::Gemini, p.path(), &encode(&bad).unwrap(), |_| panic!(
+ "wrong event probe"
+ ))
+ .is_err()
+ );
+ assert_eq!(fs::read(dir.join("counters.json")).unwrap(), before);
+ }
+ let lease = lock(&dir.join("state.lock")).unwrap();
+ assert!(handle_with(Host::Gemini, p.path(), &e, |_| panic!("busy probe")).is_err());
+ drop(lease);
+ fs::write(dir.join("counters.json"), b"{bad").unwrap();
+ assert!(handle_with(Host::Gemini, p.path(), &e, |_| panic!("corrupt probe")).is_err());
+}
+
+#[test]
+fn gemini_refusals_preserve_settings_and_failed_publication_is_recoverable() {
+ for bad in [
+ json!([]),
+ json!({"hooks":false}),
+ json!({"hooks":{"AfterTool":false}}),
+ json!({"hooksConfig":{"enabled":false}}),
+ ] {
+ let p = project();
+ fs::create_dir(p.path().join(".gemini")).unwrap();
+ let settings = p.path().join(Host::Gemini.settings());
+ let bytes = encode(&bad).unwrap();
+ fs::write(&settings, &bytes).unwrap();
+ assert!(gemini_install(p.path(), false, false).is_err());
+ assert_eq!(fs::read(settings).unwrap(), bytes);
+ assert!(!p.path().join(Host::Gemini.directory()).exists());
+ }
+ let p = project();
+ gemini_install(p.path(), false, false).unwrap();
+ let settings = p.path().join(Host::Gemini.settings());
+ let config_path = p.path().join(Host::Gemini.directory()).join("config.json");
+ let config = fs::read(&config_path).unwrap();
+ let first = fs::read(&settings).unwrap();
+ let error = configure_with(
+ Host::Gemini,
+ p.path(),
+ "http://127.0.0.1:9200",
+ (false, true),
+ Path::new("/bin/xerj"),
+ |_, _| anyhow::bail!("injected failure"),
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("injected failure"));
+ assert_eq!(fs::read(&config_path).unwrap(), config);
+ assert_eq!(fs::read(&settings).unwrap(), first);
+ for duplicate in [false, true] {
+ let mut changed: Value = serde_json::from_slice(&first).unwrap();
+ if duplicate {
+ let g = changed["hooks"]["AfterTool"][0].clone();
+ changed["hooks"]["AfterTool"]
+ .as_array_mut()
+ .unwrap()
+ .push(g);
+ } else {
+ changed["hooks"]["AfterTool"][0]["matcher"] = json!(".*");
+ }
+ let changed = encode(&changed).unwrap();
+ fs::write(&settings, &changed).unwrap();
+ assert!(gemini_install(p.path(), false, true).is_err());
+ assert_eq!(fs::read(&settings).unwrap(), changed);
+ assert_eq!(fs::read(&config_path).unwrap(), config);
+ }
+ fs::write(&settings, first).unwrap();
+ gemini_install(p.path(), false, true).unwrap();
+}
diff --git a/tools/search-hints/README.md b/tools/search-hints/README.md
index a37887099..5d10466e9 100644
--- a/tools/search-hints/README.md
+++ b/tools/search-hints/README.md
@@ -1,4 +1,4 @@
-# Advisory search hints for Claude Code
+# Advisory search hints for Claude Code and Gemini CLI
Opt in from the project directory (macOS/Linux):
@@ -12,6 +12,35 @@ Success: init prints `enabled Claude Code search hints`. Review the new
init does not install it. This feature is separate from `xerj init --memory`;
configure/remove the two features in separate invocations.
+For Gemini CLI, add `--host gemini` to every invocation:
+
+```sh
+xerj init --hooks --host gemini --dry-run
+xerj init --hooks --host gemini
+```
+
+That writes an `AfterTool` group to `.gemini/settings.json` and keeps its private
+state in `.gemini/xerj-hints/`. `--host` accepts `claude` (the default) or
+`gemini`, may be given once, and requires `--hooks`. The two hosts are
+independent: installing or removing one never reads or rewrites the other's
+settings, backups or counters, and a project may run both at once.
+
+Gemini differences, all host-imposed. The hint is delivered on `AfterTool`,
+because `BeforeTool` has no field that reaches the model — only `AfterTool`
+appends `hookSpecificOutput.additionalContext` to the tool result, wrapped in
+`<hook_context>…</hook_context>`. The installed `timeout` is `2000`, since
+Gemini counts milliseconds where Claude counts seconds; the HTTP budget inside
+the hook is identical for both hosts. Matched tools are `grep_search`, its alias
+`search_file_content`, `glob` and `read_file`. The matcher is anchored
+(`^(…)$`) because Gemini applies it unanchored, which would otherwise catch MCP
+tools named `mcp_<server>_grep_search`. Gemini also HTML-escapes the hint's
+angle brackets, so the delivered placeholder reads `&lt;words&gt;`.
+
+Gemini reads project settings, and therefore this hook, only in a directory it
+trusts; an untrusted directory refuses to start before any hook runs. Setup is
+refused outright when `hooksConfig.enabled` is `false` in the merged settings,
+because the host would silently ignore the installed group.
+
Index this same folder under a prefix you own, using the estimate/approval
workflow in AGENTS.md. The hook only suggests searches when its configured
loopback node's catalog records a nonempty run for this exact root.
@@ -25,7 +54,9 @@ After a hint, at least ten matching tool invocations must pass before another.
Calls made while the node is offline count but do not consume a hint slot.
Counters survive hook process exits. A bounded FIFO keeps 64 session hashes;
an evicted session starts a new counter if used again. Shell grep/rg is not
-intercepted. Gemini, Windows and remote nodes are unsupported in this version.
+intercepted. Quotas, counters and session hashes are per host: a Gemini hint
+never consumes a Claude hint slot. Windows and remote nodes are unsupported in
+this version.
`--url` or `XERJ_URL` at setup selects the loopback node. Only the URL is saved.
Runtime `XERJ_AUTH`, then `XERJ_API_KEY`, then origin-checked local admin-key
@@ -51,6 +82,11 @@ xerj init --hooks --remove --dry-run
xerj init --hooks --remove
```
+Removing the Gemini host takes the same `--host gemini` it was installed with:
+`xerj init --hooks --host gemini --remove`. Everything below applies to both
+hosts, reading `.gemini/settings.json`, its `AfterTool` array and
+`.gemini/xerj-hints/` for Gemini.
+
Success: the uniquely owned group is removed; foreign groups/settings and
session memory remain. Config is disabled before settings publication; existing
backups/counters remain in private `.claude/xerj-hints/`. After removal that
@@ -82,6 +118,9 @@ python3 tools/search-hints/smoke.py --binary engine/target/release/xerj
python3 tools/search-hints/smoke.py --binary engine/target/release/xerj --authenticated
```
+Both commands exercise both hosts against one private node, including their
+coexistence and per-host quotas.
+
For the optional actual-host controlled sample, add `--claude-sample --receipt NEW.json`
(requires an already authenticated Claude Code CLI; sends the synthetic task to
your configured model). It disables host session persistence, limits each run
@@ -91,11 +130,17 @@ The default smoke commands use only a private node and a tiny synthetic Rust pro
access existing indices. See VERIFICATION.md for executed results, a controlled
before/after sample and the explicit actual-host and platform limits.
-Host schema reference: [Claude Code hooks](https://code.claude.com/docs/en/hooks#pretooluse-decision-control).
+Host schema references:
+[Claude Code hooks](https://code.claude.com/docs/en/hooks#pretooluse-decision-control)
+and [Gemini CLI hooks](https://geminicli.com/docs/hooks/reference/).
Implementation evidence: existing project-owned lifecycle hook configuration in
`engine/crates/xerj-autoindex/src/session_memory.rs:190` and catalog cohort
ownership in `engine/crates/xerj-autoindex/src/catalog.rs:620`. Nonblocking file
locking uses fs2 0.4.3 `src/unix.rs:38-39` (`LOCK_EX | LOCK_NB`, licensed
MIT/Apache-2.0; inspected in the local Cargo source). No peer implementation is
-copied. The host JSON format comes from the official Claude Code reference.
+copied. Each host's JSON format comes from that host's official reference. The
+`AfterTool`-only delivery claim was read out of the Gemini CLI 0.66.0 bundle
+(`executeToolWithHooks` in `bundle/chunk-RZ3ZVTZB.js:344483-344510`, which
+appends `additionalContext` to the tool result and has no equivalent on
+`BeforeTool`) and then confirmed against the running host; see VERIFICATION.md.
diff --git a/tools/search-hints/VERIFICATION.md b/tools/search-hints/VERIFICATION.md
index c879c7d50..4fd05d65f 100644
--- a/tools/search-hints/VERIFICATION.md
+++ b/tools/search-hints/VERIFICATION.md
@@ -93,9 +93,11 @@ backs up previous settings, disables before removal, and rolls back an ordinary
settings-write failure. The two files are not a crash transaction. A power loss
or edited group can require the documented manual owned-group restoration.
Hostile same-user races, NFS stalls, forced power loss, Linux/Windows execution,
-Gemini, remote nodes, huge catalogs, source freshness and manually deleted-index
+remote nodes, huge catalogs, source freshness and manually deleted-index
recovery were not tested. The catalog cap intentionally abstains beyond 200 run
records. No model, ANN, performance, relevance or spontaneous adoption claim.
+Gemini CLI was out of scope for this section and is covered by the dated
+Gemini CLI section at the end of this file.
No engine schema migration, accelerator, cluster, telemetry or deployment change;
those review sections are not applicable. No landing files are changed. Hosted
merge-ref CI is separate from the local receipts below.
@@ -172,3 +174,176 @@ lockfile serving the executable/gates above are unchanged. The upstream function
and workflow are preserved; they are not part of this PR's effective diff.
The newly merged plain-Node function tests and workflow timeout guard passed;
Rust tests were not repeated for that JavaScript-only upstream composition.
+
+# Gemini CLI host verification — 2026-11-03
+
+Written and executed by OpenAI Codex, operated by @Jarvis636431, on macOS arm64
+with Rust 1.97.1. Independent branch based on upstream `b003bd83c`, which already
+contains the merged Claude Code hints (#2869); this section only adds the second
+host. The diff contains no Cargo dependency/lockfile, node API, storage, workflow
+or MCP schema change, and no landing file. The candidate is a source-built
+rc.100 binary, not a published-release claim.
+
+## What the host actually does, and how that was established
+
+Gemini's `BeforeTool` has no field that reaches the model. Only `AfterTool`
+returns `hookSpecificOutput.additionalContext`, and the host appends it to the
+tool result as `<hook_context>…</hook_context>`. Read first out of the pinned
+Gemini CLI 0.66.0 bundle (`executeToolWithHooks`,
+`bundle/chunk-RZ3ZVTZB.js:344483-344510`, with the same function at the tail of
+`bundle/core-FXOG6GGI.js`), then confirmed against the running host below. That
+is why this host uses `AfterTool` while Claude keeps `PreToolUse`.
+
+Gemini's hook `timeout` is milliseconds (default 60000) per the official hooks
+reference, so the installed group carries `2000` where Claude carries `2`. The
+HTTP budget inside the hook is unchanged and identical for both hosts.
+
+Gemini applies a hook `matcher` as an unanchored regular expression, so
+`grep_search` would also match `mcp_<server>_grep_search`. The installed matcher
+is therefore `^(grep_search|search_file_content|glob|read_file)$`, asserted
+positively and negatively in both the unit test and the smoke harness.
+
+Two host preconditions are reported rather than worked around. Gemini reads
+project settings only in a directory it trusts; an untrusted directory refuses
+to start before any hook runs (observed: exit 55 with the trusted-folders
+message). And `hooksConfig.enabled: false` in the merged settings switches all
+hooks off (`bundle/gemini-22EOGL6O.js:8676`), so setup refuses instead of
+installing a group the host would ignore.
+
+## Failing controls and regression coverage
+
+Before implementation, `gemini_search_hints_require_explicit_host_and_hooks`
+failed with "Gemini search hints must accept an explicit host". It passes after
+implementation.
+
+Three temporary mutations on the final source, each reverted immediately:
+
+- `timeout` 2000 → 2 failed `gemini_install_uses_after_tool_and_milliseconds_and_preserves_both_hosts`
+ at `left: Number(2), right: 2000`.
+- Unanchoring the matcher failed the same test at `assertion failed: !matcher.is_match(name)`.
+- `AfterTool` → `BeforeTool` failed all three new hook tests, including
+ `gemini_refusals_preserve_settings_and_failed_publication_is_recoverable`.
+
+Coverage in `engine/crates/xerj-autoindex/src/search_hints/tests.rs`: dry-run
+writing nothing, merge into foreign `BeforeTool`/`AfterTool` arrays, idempotence,
+binary-path and URL update, settings backup, the matcher's positive and negative
+samples, millisecond timeout, `--host gemini` in the installed command, the third
+`read_file`, ten-call spacing, `search_file_content` alias, per-session and
+per-host counters, offline silence that consumes no hint slot, no tool input or
+tool response in local state, wrong event/tool/cwd refusal, busy lock, corrupt
+counters, malformed settings, `hooksConfig.enabled: false` refusal, failed
+publication rollback, and removal that restores the original settings exactly.
+No existing test was weakened: both hosts are asserted to leave each other's
+settings bytes unchanged.
+
+## Commands
+
+From `engine/`:
+
+```sh
+CARGO_INCREMENTAL=0 TMPDIR=/private/tmp cargo test --locked -p xerj-autoindex -- --skip content::tests::lossy_display_collisions_keep_distinct_alias_identities --skip corpus_data_skip_tests::corpus_index_summary_splits_indexed_extensions_from_ignored_data --skip inventory_delta_tests::a_non_utf8_excluded_name_is_matched_on_disk_via_path_id
+CARGO_INCREMENTAL=0 TMPDIR=/private/tmp cargo test --locked -p xerj-autoindex --lib gemini
+cargo clippy --locked -p xerj-autoindex --all-targets -- -D warnings -A dead_code
+cargo fmt --all -- --check
+CARGO_INCREMENTAL=0 TMPDIR=/private/tmp cargo build --release -j 32 -p xerj-server --bin xerj
+```
+
+From the repository root:
+
+```sh
+python3 tools/search-hints/smoke.py --binary engine/target/release/xerj
+python3 tools/search-hints/smoke.py --binary engine/target/release/xerj --authenticated
+python3 .github/scripts/workflow-timeout-guard.py
+PYTHONPYCACHEPREFIX=/tmp/xerj-hint-pycache python3 -m py_compile tools/search-hints/smoke.py
+git diff --check
+```
+
+The three explicit filters are the previously documented macOS filename cases;
+the changed code does not touch those paths. The `dead_code` allowance is for
+existing `content::resolve_reporting`, the only warning in the release build.
+The scoped release build is `-p xerj-server --bin xerj` because that crate owns
+the `xerj` binary the host actually executes; no workspace-wide build and no
+`cargo clean` was used.
+
+## Receipts
+
+Complete crate run: **2041 passed, 0 failed, 5 existing ignored, 3 existing
+macOS filters**, across 12 test/doc summary groups. Focused Gemini run:
+**4 passed, 0 failed**. An earlier sandboxed attempt reported 255 failures that
+were all `PermissionDenied` on loopback bind; rerunning with loopback permission
+gave the result above, and no test or source was changed between the two runs.
+
+The release executable under test has SHA-256
+`4aac9ac029fa055c98ba0125ac884fbf610bc749e99997809a7d771482d76f4e`.
+
+Both smoke modes passed **52 installed hook invocations each**, every one exit 0
+with empty stderr, and both private nodes per mode stopped with exit 0. The
+harness now runs the Gemini lifecycle against the same private node: dry-run
+writing nothing, merge into foreign settings, idempotence, the anchored matcher's
+positive and negative samples, the millisecond timeout, the third `read_file`,
+nine spaced `grep_search` calls then `glob`, the `search_file_content` alias,
+malformed and oversized input, wrong event/tool/cwd, removal restoring the
+foreign settings byte-for-byte, the `hooksConfig.enabled: false` refusal,
+reinstallation, and both hosts hinting in one project. It also asserts that
+installing or removing one host leaves the other's settings bytes identical, and
+that a Gemini replay consumes no Claude hint slot. The fixture was
+**2 files / 1.4 KB / 3 records**; the indexing wall was **0.9 s**. These are
+fixture receipts, not throughput benchmarks.
+
+### Actual-host delivery, end to end
+
+A local script ran the pinned Gemini CLI **0.66.0** (npm tarball integrity
+checked, unpacked bundle, `node bundle/gemini.js --version` → `0.66.0`) against a
+loopback stub model, in a throwaway project where the real release binary had
+just run `xerj autoindex … --prefix gemini-e2e` and
+`xerj init --hooks --host gemini`. No credentials and no external traffic: the
+stub answers `generateContent` with one `glob` call and then a final text turn.
+
+Installed group, read back from `.gemini/settings.json`:
+
+```json
+{"matcher": "^(grep_search|search_file_content|glob|read_file)$",
+ "hooks": [{"type": "command",
+ "command": "'<tmp>/xerj' init hook --project '<tmp>/project' --host gemini",
+ "timeout": 2000}]}
+```
+
+The request the host then sent to the model carried, verbatim:
+
+```json
+{"functionResponse": {"id": "glob_…", "name": "glob", "response": {"output":
+ "Found 1 file(s) matching \"**/*.rs\" within <tmp>/project, sorted by modification time (newest first):\n<tmp>/project/src/lib.rs\n\n<hook_context>This folder has an indexed XERJ corpus: try `xerj search --prefix gemini-e2e --url 'http://127.0.0.1:…' \"&lt;words&gt;\"` or `xerj def --prefix gemini-e2e --url 'http://127.0.0.1:…' \"&lt;symbol&gt;\"` for cited passages.</hook_context>"}}}
+```
+
+Gemini exited 0, the tool result was preserved ahead of the hint, and the node
+stopped with exit 0. Note the host HTML-escapes the hint's angle brackets, so
+the delivered placeholders read `&lt;words&gt;` and `&lt;symbol&gt;`; the hint
+text is identical for both hosts and was not specialised to hide this.
+
+This proves delivery into the model request. It is **not** an uptake, relevance
+or adoption measurement: the stub model cannot choose to follow a hint, so the
+controlled before/after uptake sample exists for Claude Code only.
+
+### ES-YAML conformance gate
+
+Fresh private node from the same release executable, with the unchanged runner:
+
+```sh
+engine/target/ci-test/es-yaml-runner --url <fresh-private-loopback-node> --dir engine/tests/es-compat-yaml/yaml
+```
+
+Observed **1453 passed, 0 failed, 10 skipped**, 1463 total, 233 files, runner
+exit 0, retaining **74 catch-lenient cases** under the existing suite policy.
+That matches the totals recorded for #2869. The private node stopped with exit
+0 and its temporary data directory was removed. No suite, assertion, catch
+policy or production node was changed. This is the repository suite, not
+complete ES protocol coverage. Hosted merge-ref CI remains pending.
+
+### Not tested
+
+Gemini CLI versions other than 0.66.0, interactive Gemini sessions, a real
+Gemini model or account, Gemini on Linux or Windows, Gemini extensions or
+`~/.gemini` user-scope hooks, and spontaneous hint uptake by a real model.
+Hostile same-user races, NFS stalls, forced power loss, remote nodes and huge
+catalogs remain untested as in the section above. No model, ANN, performance or
+relevance claim is made.
diff --git a/tools/search-hints/smoke.py b/tools/search-hints/smoke.py
index 4a7bf57d4..80429ebf4 100644
--- a/tools/search-hints/smoke.py
+++ b/tools/search-hints/smoke.py
@@ -1,10 +1,14 @@
#!/usr/bin/env python3
-"""Isolated real-node lifecycle and installed PreToolUse command verification."""
+"""Isolated real-node lifecycle and installed hook command verification.
+
+Covers both hosts: Claude Code `PreToolUse` and Gemini CLI `AfterTool`.
+"""
import argparse
import hashlib
import json
import os
from pathlib import Path
+import re
import socket
import shutil
import shlex
@@ -50,6 +54,8 @@ def main():
'[limits]\ndisk_flood_stage_percent=99\n')
settings = project / '.claude/settings.json'
state = project / '.claude/xerj-hints'
+ gemini_settings = project / '.gemini/settings.json'
+ gemini_state = project / '.gemini/xerj-hints'
node = None
logs = []
commands = 0
@@ -128,6 +134,31 @@ def main():
assert not result.stdout, result.stdout
return result.stdout
+ def gemini_hook(tool='grep_search', sid='sample', expect=False, payload=None, command=None):
+ """Invoke the installed Gemini CLI command exactly as AfterTool would."""
+ nonlocal commands
+ if command is None:
+ command = json.loads(gemini_settings.read_text())['hooks']['AfterTool'][-1]['hooks'][0]['command']
+ if payload is None:
+ payload = json.dumps({'hook_event_name': 'AfterTool', 'cwd': str(project),
+ 'session_id': sid, 'tool_name': tool,
+ 'tool_input': {'pattern': 'PRIVATE_QUERY_DO_NOT_STORE'},
+ 'tool_response': {'output': 'PRIVATE_RESULT_DO_NOT_STORE'}})
+ result = subprocess.run(command, shell=True, cwd=project, env=env, input=payload,
+ text=True, capture_output=True, timeout=4)
+ commands += 1
+ assert result.returncode == 0 and not result.stderr, result
+ if expect:
+ value = json.loads(result.stdout)
+ assert list(value) == ['hookSpecificOutput'], value
+ specific = value['hookSpecificOutput']
+ assert set(specific) == {'hookEventName', 'additionalContext'}, value
+ assert specific['hookEventName'] == 'AfterTool', value
+ assert '--prefix hint-smoke' in specific['additionalContext'] and url in specific['additionalContext'], value
+ else:
+ assert not result.stdout, result.stdout
+ return result.stdout
+
try:
assert not settings.exists()
cli('init', '--hooks', '--dry-run', '--url', url)
@@ -194,6 +225,64 @@ def main():
memory = (project / '.claude/settings.local.json').read_bytes()
mapped = cli('autoindex', 'map', '--prefix', 'hint-smoke', '--url', url)
assert 'hint-smoke' in mapped.stdout, mapped
+ # Gemini CLI host (#2642): AfterTool, .gemini/settings.json, millisecond timeout.
+ assert not gemini_settings.exists()
+ cli('init', '--hooks', '--host', 'gemini', '--dry-run', '--url', url)
+ assert not gemini_settings.exists() and not gemini_state.exists()
+ gemini_settings.parent.mkdir(parents=True, exist_ok=True)
+ gemini_foreign = {'mcpServers': {}, 'hooks': {'BeforeTool': [
+ {'matcher': 'run_shell_command', 'hooks': [{'type': 'command', 'command': 'echo foreign'}]}]}}
+ gemini_settings.write_text(json.dumps(gemini_foreign))
+ cli('init', '--hooks', '--host', 'gemini', '--url', url)
+ gemini_first = gemini_settings.read_bytes()
+ cli('init', '--hooks', '--host', 'gemini', '--url', url)
+ assert gemini_settings.read_bytes() == gemini_first
+ assert settings.read_bytes() == first, 'Gemini setup must not change Claude settings'
+ gemini_group = json.loads(gemini_first)['hooks']['AfterTool'][-1]
+ assert json.loads(gemini_first)['hooks']['BeforeTool'] == gemini_foreign['hooks']['BeforeTool']
+ assert gemini_group['hooks'][0]['timeout'] == 2000, gemini_group
+ assert gemini_group['hooks'][0]['command'].endswith(' --host gemini'), gemini_group
+ matcher = re.compile(gemini_group['matcher'])
+ assert all(matcher.search(name) for name in
+ ('grep_search', 'search_file_content', 'glob', 'read_file')), gemini_group
+ assert not any(matcher.search(name) for name in
+ ('mcp_other_grep_search', 'read_many_files', 'run_shell_command')), gemini_group
+ # Controlled replay on the Gemini tool names; no actual agent/model is simulated.
+ gemini_hook('read_file', sid='g-reads')
+ gemini_hook('read_file', sid='g-reads')
+ gemini_hook('read_file', sid='g-reads', expect=True)
+ for _ in range(9):
+ gemini_hook('grep_search', sid='g-reads')
+ gemini_hook('glob', sid='g-reads', expect=True)
+ gemini_hook('search_file_content', sid='g-fresh', expect=True)
+ # Per-host counters: the Gemini replay above consumed no Claude hint slot.
+ hook(sid='g-fresh', expect=True)
+ gemini_hook(payload='{broken')
+ gemini_hook(payload='x' * 65537)
+ for field, value in [('tool_name', 'mcp_other_grep_search'), ('tool_name', 'Grep'),
+ ('hook_event_name', 'BeforeTool'), ('hook_event_name', 'PreToolUse'),
+ ('cwd', str(work))]:
+ event = {'hook_event_name': 'AfterTool', 'cwd': str(project),
+ 'session_id': 'g-wrong', 'tool_name': 'grep_search'}
+ event[field] = value
+ gemini_hook(payload=json.dumps(event))
+ gemini_counters = (gemini_state / 'counters.json').read_text()
+ assert 'PRIVATE_QUERY_DO_NOT_STORE' not in gemini_counters, gemini_counters
+ assert 'PRIVATE_RESULT_DO_NOT_STORE' not in gemini_counters, gemini_counters
+ assert 'g-fresh' not in gemini_counters, gemini_counters
+ cli('init', '--hooks', '--host', 'gemini', '--remove', '--url', url)
+ assert json.loads(gemini_settings.read_text()) == gemini_foreign
+ gemini_hook(command=gemini_group['hooks'][0]['command'])
+ assert settings.read_bytes() == first, 'Gemini removal must not change Claude settings'
+ # Hosts with hooks switched off entirely are refused without rewriting settings.
+ disabled = dict(gemini_foreign, hooksConfig={'enabled': False})
+ gemini_settings.write_text(json.dumps(disabled))
+ cli('init', '--hooks', '--host', 'gemini', '--url', url, expected=1)
+ assert json.loads(gemini_settings.read_text()) == disabled
+ gemini_settings.write_text(json.dumps(gemini_foreign))
+ cli('init', '--hooks', '--host', 'gemini', '--url', url)
+ gemini_hook(sid='g-both', expect=True)
+ hook(sid='g-both', expect=True)
# Controlled replay: Read x3, Grep x9, Glob; no actual agent/model is simulated.
hook('Read', sid='reads')
hook('Read', sid='reads')
@@ -219,6 +308,7 @@ def main():
hook(sid='restarted', expect=True)
cli('autoindex', 'remove', '--prefix', 'hint-smoke', '--root', str(project), '--url', url, '--yes')
hook(sid='removed-corpus')
+ gemini_hook(sid='g-removed-corpus')
saved = json.loads(settings.read_text())
owned = saved['hooks']['PreToolUse'][-1]
saved['hooks']['PreToolUse'][-1]['matcher'] = 'Bash'
@@ -236,7 +326,8 @@ def main():
assert (project / '.claude/settings.local.json').read_bytes() == memory
cli('init', '--hooks', '--url', url)
stop()
- print(f'PASS: {commands} installed hook invocations; lifecycle, limits, scope, refusal/recovery and removal', flush=True)
+ print(f'PASS: {commands} installed hook invocations across both hosts; '
+ 'lifecycle, limits, scope, refusal/recovery and removal', flush=True)
finally:
stop()
for log in logs: