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 Claude Code search hints (#2869)

Jarvis4ed4d615421b
diff --git a/.gitignore b/.gitignore
index d7f88593a..a0ebe7d1d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -218,3 +218,6 @@ scripts/seo/evidence/
# (plugins/<name>/skills/<skill>/SKILL.md, plugins/<name>/commands/*.md).
!plugins/*/skills/**/*.md
!plugins/*/commands/*.md
+
+# Advisory hook documentation and reproducible verification (#2642).
+!tools/search-hints/*.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04f7358db..df8e65277 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Opt-in advisory Claude Code search hints with `xerj init --hooks` on macOS/Linux
+ (Refs #2642): Grep/Glob and repeated Read can suggest a cited search scoped to
+ the indexed folder and configured loopback node, with a per-session quota.
+ `--hooks --remove` preserves other hooks and session memory.
+
- 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 be9a7277f..3a2c602d3 100644
--- a/docs/RERANK.md
+++ b/docs/RERANK.md
@@ -411,6 +411,10 @@ the picture:
indexing/memory storage, and reads memories back for SessionStart. It refuses
remote URLs and disables redirects and proxies; it adds no node-side egress.
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.
`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 b0a49f995..f866eb8ee 100644
--- a/docs/recipes/air-gapped-deployment.md
+++ b/docs/recipes/air-gapped-deployment.md
@@ -48,6 +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 |
| `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 740bb96e2..d0e75cb38 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)
- --remove with --memory, remove only these hooks; keep private data
+ --hooks opt in to advisory Claude Code search hints (macOS/Linux)
+ --remove with --memory or --hooks, remove only that feature; keep data
--disable-feedback
accepted; turns off the feedback invitation on help
screens. Honoured in any position (env XERJ_DISABLE_FEEDBACK)
@@ -78,6 +79,13 @@ gets bounded, cited excerpts, not an LLM summary. No key is saved. Private
archives and pending work stay in .claude/xerj-memory/; --remove retains them.
Read tools/session-memory/README.md for limits, inspection and deletion.
+With --hooks, init merges an advisory PreToolUse hook into .claude/settings.json.
+Grep/Glob or the third Read can suggest a project-scoped search when the loopback
+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.
+
After ordinary init: restart the agent session so it picks up the new tools, then
`xerj autoindex <folder> --prefix <name>` anything you want searchable.
Pass that same `--prefix <name>` to `xerj search` and `xerj def`; without it
@@ -118,6 +126,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\
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\
@@ -583,6 +592,7 @@ struct InitFlags {
dry: bool,
help: bool,
memory: bool,
+ hooks: bool,
remove: bool,
}
@@ -594,6 +604,7 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
.unwrap_or_else(|| DEFAULT_URL.to_string());
let mut dry = false;
let mut memory = false;
+ let mut hooks = false;
let mut remove = false;
let mut it = args.into_iter();
while let Some(a) = it.next() {
@@ -604,12 +615,14 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
dry,
help: true,
memory,
+ hooks,
remove,
});
}
"--url" => url = it.next().unwrap_or(url),
"--dry-run" => dry = true,
"--memory" => memory = true,
+ "--hooks" => hooks = true,
"--remove" => remove = true,
// Also stripped by args_after_subcommand. Accepted here so a
// caller that passes the raw list still does not exit 2.
@@ -617,20 +630,30 @@ fn read_init_flags(args: impl IntoIterator<Item = String>) -> Result<InitFlags,
other => return Err(format!("xerj init: unexpected argument '{other}'")),
}
}
- if remove && !memory {
- return Err("xerj init: --remove requires --memory".into());
+ if remove && !memory && !hooks {
+ return Err("xerj init: --remove requires --memory or --hooks".into());
+ }
+ if memory && hooks {
+ return Err("xerj init: configure --memory and --hooks separately".into());
}
Ok(InitFlags {
url,
dry,
help: false,
memory,
+ hooks,
remove,
})
}
#[cfg(test)]
mod memory_flag_regression {
+ #[test]
+ fn search_hints_are_an_explicit_separate_opt_in() {
+ assert!(super::read_init_flags(["--hooks", "--dry-run"].map(String::from)).is_ok());
+ assert!(super::read_init_flags(["--hooks", "--remove"].map(String::from)).is_ok());
+ assert!(super::read_init_flags(["--hooks", "--memory"].map(String::from)).is_err());
+ }
#[test]
fn memory_hooks_are_an_explicit_init_opt_in() {
assert!(super::read_init_flags(["--remove".into()])
@@ -660,11 +683,15 @@ pub fn run_init_cli() -> i32 {
let url = flags.url;
let dry = flags.dry;
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
- if flags.memory {
+ if flags.memory || flags.hooks {
let result = std::env::current_exe()
.map_err(anyhow::Error::from)
.and_then(|binary| {
- crate::session_memory::configure(&cwd, &url, dry, flags.remove, &binary)
+ if flags.hooks {
+ crate::search_hints::configure(&cwd, &url, dry, flags.remove, &binary)
+ } else {
+ crate::session_memory::configure(&cwd, &url, dry, flags.remove, &binary)
+ }
});
return match result {
Ok(lines) => {
@@ -674,7 +701,10 @@ pub fn run_init_cli() -> i32 {
0
}
Err(error) => {
- eprintln!("xerj init --memory: {error}");
+ eprintln!(
+ "xerj init {}: {error}",
+ if flags.hooks { "--hooks" } else { "--memory" }
+ );
1
}
};
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index c2b251253..8f40a6bcd 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -50,6 +50,7 @@ mod reconcile_plan;
pub mod remove;
pub mod resources;
pub mod search;
+pub mod search_hints;
mod session_memory;
pub mod sessions;
pub mod skills;
diff --git a/engine/crates/xerj-autoindex/src/search_hints.rs b/engine/crates/xerj-autoindex/src/search_hints.rs
new file mode 100644
index 000000000..9c490b022
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/search_hints.rs
@@ -0,0 +1,422 @@
+//! Opt-in, advisory-only Claude Code PreToolUse hints (#2642).
+//! Host contract: https://code.claude.com/docs/en/hooks#pretooluse-decision-control.
+//! Return additionalContext only: never permissionDecision, updatedInput or exit 2.
+use anyhow::{ensure, Context, Result};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::fs;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+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";
+const LIMIT: u64 = 64 * 1024;
+const INTERVAL: u64 = 10;
+const MAX_SESSIONS: usize = 64;
+
+#[derive(Serialize, Deserialize)]
+struct Config {
+ version: u32,
+ enabled: bool,
+ project: PathBuf,
+ url: String,
+ group: Value,
+}
+
+fn group(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
+ }]}))
+}
+
+pub(crate) fn configure(
+ project: &Path,
+ url: &str,
+ dry: bool,
+ remove: bool,
+ binary: &Path,
+) -> Result<Vec<String>> {
+ configure_with(project, url, dry, remove, binary, atomic)
+}
+
+fn configure_with(
+ project: &Path,
+ url: &str,
+ dry: bool,
+ remove: bool,
+ binary: &Path,
+ publish_settings: impl FnOnce(&Path, &[u8]) -> Result<()>,
+) -> Result<Vec<String>> {
+ ensure!(
+ cfg!(unix),
+ "search hint hooks currently support macOS and Linux only"
+ );
+ let project = project.canonicalize()?;
+ loopback(url)?;
+ let url = reqwest::Url::parse(url)?.to_string();
+ let dir = project.join(DIRECTORY);
+ let config_path = dir.join("config.json");
+ let path = project.join(SETTINGS);
+ let old = read(&path, 1024 * 1024)?;
+ let old_config = read(&config_path, LIMIT)?;
+ let previous: Option<Config> = old_config
+ .as_deref()
+ .map(serde_json::from_slice)
+ .transpose()?;
+ if let Some(p) = &previous {
+ ensure!(
+ p.version == 1 && p.project == project,
+ "foreign or unsupported search hint configuration"
+ );
+ }
+ let mut settings: Value = old
+ .as_deref()
+ .map(serde_json::from_slice)
+ .transpose()?
+ .unwrap_or(json!({}));
+ ensure!(
+ settings.is_object(),
+ "Claude settings must be an object; not touching it"
+ );
+ 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 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")?;
+ let groups = hooks
+ .entry("PreToolUse")
+ .or_insert(json!([]))
+ .as_array_mut()
+ .context("PreToolUse must be an array")?;
+ let owned = previous.as_ref().filter(|p| p.enabled);
+ if let Some(p) = owned {
+ ensure!(groups.iter().filter(|g| *g == &p.group).count() == 1,
+ "managed search hint was edited or removed; restore its group from config.json before retrying");
+ }
+ ensure!(
+ groups.iter().filter(|g| *g == &wanted).count()
+ == usize::from(owned.is_some_and(|p| p.group == wanted)),
+ "matching search hint exists without unique ownership; not touching it"
+ );
+ if let Some(p) = owned {
+ groups.retain(|g| g != &p.group);
+ }
+ if !remove {
+ groups.push(wanted.clone());
+ }
+ if groups.is_empty() {
+ hooks.remove("PreToolUse");
+ }
+ if hooks.is_empty() {
+ root.remove("hooks");
+ }
+ let next = Config {
+ version: 1,
+ enabled: !remove,
+ project: project.clone(),
+ url: url.trim_end_matches('/').into(),
+ group: wanted,
+ };
+ let bytes = encode(&settings)?;
+ let config_bytes = encode(&next)?;
+ ensure!(
+ 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()];
+ if dry {
+ return Ok(lines);
+ }
+ fs::create_dir_all(project.join(".claude"))?;
+ private_dir(&dir)?;
+ let _lease = lock(&dir.join("state.lock"))?;
+ // Serialise installers and runtime counters; refuse a stale preflight.
+ ensure!(
+ read(&path, 1024 * 1024)? == old && read(&config_path, LIMIT)? == old_config,
+ "search hint settings changed; retry"
+ );
+ atomic(&dir.join(".gitignore"), b"*\n!.gitignore\n")?;
+ if old.as_deref() == Some(&bytes) && old_config.as_deref() == Some(&config_bytes) {
+ return Ok(lines);
+ }
+ if let Some(old) = &old {
+ let backup = dir.join(format!("settings-{}.bak", &digest(old)[..16]));
+ match read(&backup, 1024 * 1024)? {
+ Some(found) => ensure!(found == *old, "search hint backup collision"),
+ None => {
+ atomic(&backup, old)?;
+ }
+ }
+ }
+ atomic(&config_path, &config_bytes)?;
+ if let Err(error) = publish_settings(&path, &bytes) {
+ match old_config {
+ Some(old) => atomic(&config_path, &old)?,
+ None => fs::remove_file(&config_path)?,
+ }
+ return Err(error);
+ }
+ Ok(lines)
+}
+
+#[derive(Default, Serialize, Deserialize)]
+struct Counters {
+ sessions: Vec<Session>,
+}
+#[derive(Serialize, Deserialize)]
+struct Session {
+ id: String,
+ calls: u64,
+ reads: u64,
+ last_hint: Option<u64>,
+}
+impl Counters {
+ fn visit(&mut self, id: &str, tool: &str) -> &mut Session {
+ let i = if let Some(i) = self.sessions.iter().position(|s| s.id == id) {
+ i
+ } else {
+ if self.sessions.len() == MAX_SESSIONS {
+ self.sessions.remove(0);
+ }
+ self.sessions.push(Session {
+ id: id.into(),
+ calls: 0,
+ reads: 0,
+ last_hint: None,
+ });
+ self.sessions.len() - 1
+ };
+ let s = &mut self.sessions[i];
+ s.calls = s.calls.saturating_add(1);
+ if tool == "Read" {
+ s.reads = s.reads.saturating_add(1);
+ }
+ s
+ }
+}
+impl Session {
+ fn eligible(&self, tool: &str) -> bool {
+ (tool != "Read" || self.reads >= 3)
+ && self
+ .last_hint
+ .is_none_or(|n| self.calls.saturating_sub(n) >= INTERVAL)
+ }
+}
+
+// Root is not a mapped catalog field (catalog.rs:660); filter the bounded
+// run documents client-side, as search.rs:643 does for legacy prefix fields.
+// Only latest cohorts with unambiguous root ownership may supply a prefix.
+fn indexed_prefix(value: &Value, project: &Path) -> Option<String> {
+ if value["timed_out"].as_bool() == Some(true)
+ || value
+ .pointer("/_shards/failed")
+ .and_then(Value::as_u64)
+ .unwrap_or(0)
+ != 0
+ {
+ return None;
+ }
+ let hits = value.pointer("/hits/hits")?.as_array()?;
+ if value.pointer("/hits/total/relation")?.as_str()? != "eq"
+ || value.pointer("/hits/total/value")?.as_u64()? > hits.len() as u64
+ {
+ return None;
+ }
+ let runs: Vec<Value> = hits.iter().map(|h| h["_source"].clone()).collect();
+ let root = project.to_str()?;
+ let mut prefixes: Vec<&str> = runs
+ .iter()
+ .filter(|r| {
+ r["doc_kind"] == "run"
+ && r["root"] == root
+ && r["records_total"].as_u64().unwrap_or(0) > 0
+ })
+ .filter_map(|r| r["prefix"].as_str())
+ .filter(|p| valid_prefix(p))
+ .collect();
+ prefixes.sort_unstable();
+ prefixes.dedup();
+ prefixes
+ .into_iter()
+ .find(|p| {
+ let latest = runs
+ .iter()
+ .filter(|r| r["doc_kind"] == "run" && r["prefix"] == *p)
+ .filter_map(|r| r["started"].as_str())
+ .max();
+ latest.is_some()
+ && crate::catalog::foreign_prefix_roots(&runs, p, root).is_empty()
+ && runs
+ .iter()
+ .filter(|r| {
+ r["doc_kind"] == "run"
+ && r["prefix"] == *p
+ && r["started"].as_str() == latest
+ })
+ .all(|r| r["records_total"].as_u64().unwrap_or(0) > 0)
+ })
+ .map(str::to_owned)
+}
+fn valid_prefix(prefix: &str) -> bool {
+ !prefix.is_empty()
+ && prefix.len() <= 128
+ && prefix
+ .bytes()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
+}
+fn probe(config: &Config) -> Result<Option<String>> {
+ let mut headers = reqwest::header::HeaderMap::new();
+ // An explicit runtime key wins; discovery must belong to this node.
+ let auth = std::env::var("XERJ_AUTH")
+ .ok()
+ .filter(|s| !s.is_empty())
+ .or_else(|| {
+ std::env::var("XERJ_API_KEY")
+ .ok()
+ .filter(|s| !s.is_empty())
+ .map(|s| format!("ApiKey {s}"))
+ })
+ .or_else(|| {
+ let key =
+ xerj_common::localauth::discover_local_admin_key_for_url_with_origin(&config.url)?;
+ key.foreign_warning("XERJ_AUTH")
+ .is_none()
+ .then(|| format!("ApiKey {}", key.key))
+ });
+ if let Some(auth) = auth {
+ headers.insert(reqwest::header::AUTHORIZATION, auth.parse()?);
+ }
+ let client = reqwest::blocking::Client::builder()
+ .no_proxy()
+ .redirect(reqwest::redirect::Policy::none())
+ .connect_timeout(Duration::from_millis(100))
+ .timeout(Duration::from_millis(300))
+ .default_headers(headers)
+ .build()?;
+ let response = client
+ .post(format!("{}/autoindex-catalog/_search", config.url))
+ .json(&json!({
+ "size":200, "track_total_hits":true, "query":{"term":{"doc_kind":"run"}},
+ "_source":["doc_kind","root","prefix","started","records_total"]
+ }))
+ .send()?
+ .error_for_status()?;
+ ensure!(
+ response.status().is_success(),
+ "catalog did not return success"
+ );
+ let mut bytes = Vec::new();
+ response.take(256 * 1024 + 1).read_to_end(&mut bytes)?;
+ ensure!(bytes.len() <= 256 * 1024, "catalog response over budget");
+ Ok(indexed_prefix(
+ &serde_json::from_slice(&bytes)?,
+ &config.project,
+ ))
+}
+
+fn handle(project: &Path, input: &[u8]) -> Result<Option<Value>> {
+ handle_with(project, input, probe)
+}
+fn handle_with(
+ project: &Path,
+ input: &[u8],
+ probe: impl FnOnce(&Config) -> Result<Option<String>>,
+) -> Result<Option<Value>> {
+ ensure!(
+ cfg!(unix) && input.len() as u64 <= LIMIT,
+ "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");
+ let sid = event["session_id"]
+ .as_str()
+ .filter(|s| !s.is_empty() && s.len() <= 256)
+ .context("invalid session id")?;
+ 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 config: Config =
+ serde_json::from_slice(&read(&dir.join("config.json"), LIMIT)?.context("not configured")?)?;
+ ensure!(
+ config.version == 1 && config.enabled && config.project == project,
+ "disabled or foreign configuration"
+ );
+ loopback(&config.url)?;
+ private_dir(&dir)?;
+ let _lease = lock(&dir.join("state.lock"))?;
+ // Recheck under the installer lock, so removal cannot race a late hint.
+ let current = read(&dir.join("config.json"), LIMIT)?.context("not configured")?;
+ ensure!(current == encode(&config)?, "configuration changed");
+ let path = dir.join("counters.json");
+ let mut counters: Counters = read(&path, LIMIT)?
+ .as_deref()
+ .map(serde_json::from_slice)
+ .transpose()?
+ .unwrap_or_default();
+ ensure!(
+ counters.sessions.len() <= MAX_SESSIONS,
+ "oversized counters"
+ );
+ let session = counters.visit(&digest(sid.as_bytes()), tool);
+ let prefix = if session.eligible(tool) {
+ probe(&config).ok().flatten()
+ } else {
+ None
+ };
+ let endpoint = quote(
+ reqwest::Url::parse(&config.url)?
+ .as_str()
+ .trim_end_matches('/'),
+ );
+ let output = prefix.map(|prefix| {
+ session.last_hint = Some(session.calls);
+ json!({"hookSpecificOutput":{"hookEventName":"PreToolUse", "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)?)?;
+ Ok(output)
+}
+
+/// Internal command, deliberately dispatched before node/runtime setup.
+/// Malformed input, unavailable node, lock contention and I/O all abstain silently.
+pub fn run(args: &[String]) -> i32 {
+ let result = (|| -> Result<Option<Value>> {
+ ensure!(
+ args.len() == 2 && args[0] == "--project",
+ "invalid arguments"
+ );
+ let mut bytes = Vec::new();
+ std::io::stdin().take(LIMIT + 1).read_to_end(&mut bytes)?;
+ handle(Path::new(&args[1]), &bytes)
+ })();
+ if let Ok(Some(value)) = result {
+ use std::io::Write;
+ let _ = writeln!(std::io::stdout().lock(), "{value}");
+ }
+ 0
+}
+
+#[cfg(all(test, unix))]
+mod tests;
diff --git a/engine/crates/xerj-autoindex/src/search_hints/tests.rs b/engine/crates/xerj-autoindex/src/search_hints/tests.rs
new file mode 100644
index 000000000..920c904f2
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/search_hints/tests.rs
@@ -0,0 +1,421 @@
+use super::*;
+fn project() -> tempfile::TempDir {
+ tempfile::tempdir().unwrap()
+}
+fn install(p: &Path, dry: bool, remove: bool) -> Result<Vec<String>> {
+ configure(
+ p,
+ "http://127.0.0.1:9200",
+ dry,
+ remove,
+ Path::new("/opt/xerj's bin/xerj"),
+ )
+}
+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()
+}
+#[test]
+fn dry_run_merge_reconfigure_remove_and_memory_coexistence() {
+ let p = project();
+ install(p.path(), true, false).unwrap();
+ assert_eq!(fs::read_dir(p.path()).unwrap().count(), 0);
+ fs::create_dir(p.path().join(".claude")).unwrap();
+ let original = json!({"permissions":{"allow":["Read"]},"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[]}],"Stop":[{"hooks":[]}]}});
+ let settings = p.path().join(SETTINGS);
+ fs::write(&settings, encode(&original).unwrap()).unwrap();
+ crate::session_memory::configure(
+ p.path(),
+ "http://127.0.0.1:9200",
+ false,
+ false,
+ Path::new("/bin/xerj"),
+ )
+ .unwrap();
+ let memory = fs::read(p.path().join(".claude/settings.local.json")).unwrap();
+ install(p.path(), false, false).unwrap();
+ let first = fs::read(&settings).unwrap();
+ install(p.path(), false, false).unwrap();
+ assert_eq!(first, fs::read(&settings).unwrap());
+ let groups: Value = serde_json::from_slice(&first).unwrap();
+ assert_eq!(groups["hooks"]["PreToolUse"].as_array().unwrap().len(), 2);
+ let cmd = groups["hooks"]["PreToolUse"][1]["hooks"][0]["command"]
+ .as_str()
+ .unwrap();
+ assert!(cmd.contains("'\\''"));
+ configure(
+ p.path(),
+ "http://127.0.0.1:9201",
+ false,
+ false,
+ Path::new("/new/bin/xerj"),
+ )
+ .unwrap();
+ let moved: Value = serde_json::from_slice(&fs::read(&settings).unwrap()).unwrap();
+ assert!(moved["hooks"]["PreToolUse"][1]["hooks"][0]["command"]
+ .as_str()
+ .unwrap()
+ .contains("/new/bin/xerj"));
+ let backups = fs::read_dir(p.path().join(DIRECTORY))
+ .unwrap()
+ .filter_map(|e| {
+ let p = e.unwrap().path();
+ (p.extension().is_some_and(|s| s == "bak")).then_some(p)
+ })
+ .collect::<Vec<_>>();
+ assert!(backups
+ .iter()
+ .any(|b| fs::read(b).unwrap() == encode(&original).unwrap()));
+ install(p.path(), false, true).unwrap();
+ 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(".claude/settings.local.json")).unwrap(),
+ memory
+ );
+ assert!(fire_after_removal(p.path()).is_err());
+}
+fn fire_after_removal(p: &Path) -> Result<Option<Value>> {
+ handle_with(p, &event(p, "x", "Grep"), |_| {
+ panic!("disabled hook contacted node")
+ })
+}
+#[test]
+fn malformed_edited_duplicated_and_foreign_configuration_refuse_without_overwrite() {
+ for bad in [
+ json!([]),
+ json!({"hooks":false}),
+ json!({"hooks":{"PreToolUse":false}}),
+ ] {
+ let p = project();
+ fs::create_dir(p.path().join(".claude")).unwrap();
+ let path = p.path().join(SETTINGS);
+ let bytes = encode(&bad).unwrap();
+ fs::write(&path, &bytes).unwrap();
+ assert!(install(p.path(), false, false).is_err());
+ assert_eq!(fs::read(path).unwrap(), bytes);
+ assert!(!p.path().join(DIRECTORY).exists());
+ }
+ for duplicated in [false, true] {
+ let p = project();
+ install(p.path(), false, false).unwrap();
+ let path = p.path().join(SETTINGS);
+ let mut settings: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
+ if duplicated {
+ let group = settings["hooks"]["PreToolUse"][0].clone();
+ settings["hooks"]["PreToolUse"]
+ .as_array_mut()
+ .unwrap()
+ .push(group);
+ } else {
+ settings["hooks"]["PreToolUse"][0]["matcher"] = json!("Bash");
+ }
+ let bytes = encode(&settings).unwrap();
+ fs::write(&path, &bytes).unwrap();
+ let config = fs::read(p.path().join(DIRECTORY).join("config.json")).unwrap();
+ assert!(install(p.path(), false, true).is_err());
+ assert_eq!(fs::read(&path).unwrap(), bytes);
+ assert_eq!(
+ fs::read(p.path().join(DIRECTORY).join("config.json")).unwrap(),
+ config
+ );
+ // Restore exactly the owned group, then the documented removal succeeds.
+ let owned: Config = serde_json::from_slice(&config).unwrap();
+ settings["hooks"]["PreToolUse"] = json!([owned.group]);
+ fs::write(&path, encode(&settings).unwrap()).unwrap();
+ install(p.path(), false, true).unwrap();
+ }
+ let p = project();
+ fs::create_dir(p.path().join(".claude")).unwrap();
+ let wanted = group(
+ &p.path().canonicalize().unwrap(),
+ Path::new("/opt/xerj's bin/xerj"),
+ )
+ .unwrap();
+ fs::write(
+ p.path().join(SETTINGS),
+ encode(&json!({"hooks":{"PreToolUse":[wanted]}})).unwrap(),
+ )
+ .unwrap();
+ assert!(install(p.path(), false, false).is_err());
+}
+#[test]
+fn rate_limit_and_read_threshold_survive_process_reloads_and_isolate_sessions() {
+ let p = project();
+ install(p.path(), false, false).unwrap();
+ assert!(fire(p.path(), "a", "Read").is_none());
+ assert!(fire(p.path(), "a", "Read").is_none());
+ let output = fire(p.path(), "a", "Read").unwrap();
+ let specific = &output["hookSpecificOutput"];
+ assert_eq!(specific.as_object().unwrap().len(), 2);
+ assert_eq!(specific["hookEventName"], "PreToolUse");
+ assert!(specific["additionalContext"]
+ .as_str()
+ .unwrap()
+ .contains("--prefix my-repo"));
+ assert!(specific["additionalContext"]
+ .as_str()
+ .unwrap()
+ .contains("--url 'http://127.0.0.1:9200'"));
+ for _ in 0..9 {
+ assert!(fire(p.path(), "a", "Grep").is_none());
+ }
+ assert!(fire(p.path(), "a", "Glob").is_some());
+ assert!(fire(p.path(), "b", "Grep").is_some());
+ let counters = fs::read_to_string(p.path().join(DIRECTORY).join("counters.json")).unwrap();
+ assert!(!counters.contains("do not send or persist"));
+ let parsed: Counters = serde_json::from_str(&counters).unwrap();
+ assert_eq!(parsed.sessions.len(), 2);
+ assert_eq!(parsed.sessions[0].calls, 13);
+}
+#[test]
+fn bounded_sessions_and_counters_busy_or_corrupt_abstain() {
+ let mut counters = Counters::default();
+ for i in 0..1000 {
+ counters.visit(&digest(i.to_string().as_bytes()), "Grep");
+ }
+ assert_eq!(counters.sessions.len(), MAX_SESSIONS);
+ let p = project();
+ 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()
+ );
+ 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()
+ );
+}
+#[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"))
+ .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());
+ }
+ let mut e: Value = serde_json::from_slice(&e).unwrap();
+ for (field, value) in [
+ ("tool_name", json!("Bash")),
+ ("hook_event_name", json!("PostToolUse")),
+ ("cwd", json!("/")),
+ ("session_id", json!("")),
+ ] {
+ let old = e[field].clone();
+ e[field] = value;
+ assert!(
+ handle_with(p.path(), &serde_json::to_vec(&e).unwrap(), |_| panic!(
+ "mismatched probe"
+ ))
+ .is_err()
+ );
+ e[field] = old;
+ }
+}
+fn catalog(runs: Vec<Value>) -> Value {
+ json!({"hits":{"total":{"value":runs.len(),"relation":"eq"},"hits":runs.into_iter().map(|s|json!({"_source":s})).collect::<Vec<_>>()}})
+}
+fn run(root: &str, prefix: &str, started: &str) -> Value {
+ json!({"doc_kind":"run","root":root,"prefix":prefix,"started":started,"records_total":3})
+}
+#[test]
+fn catalog_uses_latest_root_ownership_and_refuses_incomplete_or_injected_metadata() {
+ let root = Path::new("/work");
+ let a = run("/work", "project", "2026-01-01");
+ assert_eq!(
+ indexed_prefix(&catalog(vec![a.clone()]), root).as_deref(),
+ Some("project")
+ );
+ assert!(indexed_prefix(
+ &catalog(vec![run("/elsewhere", "project", "2026-01-01")]),
+ root
+ )
+ .is_none());
+ assert!(indexed_prefix(
+ &catalog(vec![a.clone(), run("/elsewhere", "project", "2026-01-02")]),
+ root
+ )
+ .is_none());
+ assert!(indexed_prefix(
+ &catalog(vec![a.clone(), run("/elsewhere", "project", "2026-01-01")]),
+ root
+ )
+ .is_none());
+ for prefix in ["bad;echo", "bad\n", "$(echo)", "*", "UPPER"] {
+ assert!(indexed_prefix(&catalog(vec![run("/work", prefix, "2026-01-01")]), root).is_none());
+ }
+ let mut empty = run("/work", "project", "2026-01-02");
+ empty["records_total"] = json!(0);
+ assert!(indexed_prefix(&catalog(vec![a.clone(), empty]), root).is_none());
+ for (pointer, value) in [
+ ("/hits/total/value", json!(201)),
+ ("/hits/total/relation", json!("gte")),
+ ("/timed_out", json!(true)),
+ ] {
+ let mut v = catalog(vec![a.clone()]);
+ if pointer == "/timed_out" {
+ v["timed_out"] = value;
+ } else {
+ *v.pointer_mut(pointer).unwrap() = value;
+ }
+ assert!(indexed_prefix(&v, root).is_none());
+ }
+}
+#[test]
+fn remote_urls_and_symlinks_refuse_before_settings_changes() {
+ let p = project();
+ for url in [
+ "https://example.com",
+ "http://127.0.0.1:9200/path",
+ "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_eq!(fs::read_dir(p.path()).unwrap().count(), 0);
+ }
+ #[cfg(unix)]
+ {
+ fs::create_dir(p.path().join(".claude")).unwrap();
+ let other = project();
+ let file = other.path().join("settings");
+ fs::write(&file, b"{}").unwrap();
+ std::os::unix::fs::symlink(&file, p.path().join(SETTINGS)).unwrap();
+ assert!(install(p.path(), false, false).is_err());
+ assert_eq!(fs::read(file).unwrap(), b"{}");
+ }
+}
+
+#[test]
+fn http_probe_bounds_catalog_and_never_follows_redirects_or_sends_tool_input() {
+ use std::io::{Read, Write};
+ use std::net::TcpListener;
+ for shape in ["ok", "redirect", "oversize", "partial"] {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let body = match shape {
+ "oversize" => "x".repeat(256 * 1024 + 1),
+ "partial" => {
+ json!({"hits":{"total":{"value":201,"relation":"eq"},"hits":[]}}).to_string()
+ }
+ _ => catalog(vec![run("/work", "fixture", "2026-01-01")]).to_string(),
+ };
+ let task = std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ stream
+ .set_read_timeout(Some(Duration::from_secs(3)))
+ .unwrap();
+ let mut request = Vec::new();
+ let mut buffer = [0u8; 2048];
+ loop {
+ let n = stream.read(&mut buffer).unwrap();
+ assert!(n > 0);
+ request.extend_from_slice(&buffer[..n]);
+ if let Some(i) = request.windows(4).position(|w| w == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&request[..i]).to_lowercase();
+ let len: usize = headers
+ .lines()
+ .find_map(|l| l.strip_prefix("content-length: "))
+ .unwrap()
+ .parse()
+ .unwrap();
+ if request.len() >= i + 4 + len {
+ break;
+ }
+ }
+ }
+ let status = if shape == "redirect" {
+ "302 Found\r\nLocation: http://127.0.0.1:1/never"
+ } else {
+ "200 OK"
+ };
+ let _ = write!(stream,"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
+ String::from_utf8(request).unwrap()
+ });
+ let config = Config {
+ version: 1,
+ enabled: true,
+ project: PathBuf::from("/work"),
+ url,
+ group: json!({}),
+ };
+ let got = probe(&config);
+ if shape == "ok" {
+ assert_eq!(got.unwrap().as_deref(), Some("fixture"));
+ } else if shape == "partial" {
+ assert!(got.unwrap().is_none());
+ } else {
+ assert!(got.is_err(), "{shape}");
+ }
+ let request = task.join().unwrap();
+ assert!(request.starts_with("POST /autoindex-catalog/_search HTTP/1.1"));
+ let body: Value = serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap();
+ assert_eq!(body["query"], json!({"term":{"doc_kind":"run"}}));
+ assert_eq!(body["size"], 200);
+ assert!(
+ !request.contains("PRIVATE_QUERY")
+ && !request.contains("session_id")
+ && !request.contains("tool_input")
+ );
+ }
+}
+
+#[test]
+fn failed_settings_publication_rolls_back_config_and_allows_retry() {
+ let p = project();
+ install(p.path(), false, false).unwrap();
+ 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(
+ p.path(),
+ "http://127.0.0.1:9200",
+ false,
+ true,
+ Path::new("/bin/xerj"),
+ |_, _| anyhow::bail!("injected publication failure"),
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("injected publication failure"));
+ assert_eq!(fs::read(p.path().join(SETTINGS)).unwrap(), settings);
+ assert_eq!(
+ fs::read(p.path().join(DIRECTORY).join("config.json")).unwrap(),
+ config
+ );
+ assert!(fire(p.path(), "after-failure", "Grep").is_some());
+ install(p.path(), false, true).unwrap();
+ assert!(fire_after_removal(p.path()).is_err());
+}
+
+#[test]
+fn installing_into_near_limit_settings_refuses_before_creating_unreadable_state() {
+ let p = project();
+ fs::create_dir(p.path().join(".claude")).unwrap();
+ let before = serde_json::to_vec(&json!({"padding":"x".repeat(1024*1024-100)})).unwrap();
+ assert!(before.len() < 1024 * 1024);
+ fs::write(p.path().join(SETTINGS), &before).unwrap();
+ let error = install(p.path(), false, false).unwrap_err();
+ assert!(error.to_string().contains("exceeds its read budget"));
+ assert_eq!(fs::read(p.path().join(SETTINGS)).unwrap(), before);
+ assert!(!p.path().join(DIRECTORY).exists());
+}
diff --git a/engine/crates/xerj-autoindex/src/session_memory.rs b/engine/crates/xerj-autoindex/src/session_memory.rs
index 9f49dd134..4513f786b 100644
--- a/engine/crates/xerj-autoindex/src/session_memory.rs
+++ b/engine/crates/xerj-autoindex/src/session_memory.rs
@@ -26,7 +26,7 @@ struct Config {
hooks: Value,
}
-fn digest(bytes: &[u8]) -> String {
+pub(super) fn digest(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn state(project: &Path) -> PathBuf {
@@ -45,7 +45,7 @@ fn check_path(path: &Path) -> Result<()> {
}
Ok(())
}
-fn read(path: &Path, limit: u64) -> Result<Option<Vec<u8>>> {
+pub(super) fn read(path: &Path, limit: u64) -> Result<Option<Vec<u8>>> {
check_path(path)?;
let mut options = OpenOptions::new();
options.read(true);
@@ -71,7 +71,7 @@ fn read(path: &Path, limit: u64) -> Result<Option<Vec<u8>>> {
);
Ok(Some(bytes))
}
-fn private_dir(path: &Path) -> Result<()> {
+pub(super) fn private_dir(path: &Path) -> Result<()> {
check_path(path)?;
if !path.exists() {
let mut builder = fs::DirBuilder::new();
@@ -95,7 +95,7 @@ fn private_dir(path: &Path) -> Result<()> {
}
Ok(())
}
-fn atomic(path: &Path, bytes: &[u8]) -> Result<()> {
+pub(super) fn atomic(path: &Path, bytes: &[u8]) -> Result<()> {
check_path(path)?;
let mut temp = tempfile::NamedTempFile::new_in(path.parent().context("missing parent")?)?;
temp.write_all(bytes)?;
@@ -103,12 +103,12 @@ fn atomic(path: &Path, bytes: &[u8]) -> Result<()> {
temp.persist(path).map_err(|error| error.error)?;
Ok(())
}
-fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
+pub(super) fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
let mut bytes = serde_json::to_vec_pretty(value)?;
bytes.push(b'\n');
Ok(bytes)
}
-fn lock(path: &Path) -> Result<File> {
+pub(super) fn lock(path: &Path) -> Result<File> {
check_path(path)?;
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
@@ -128,7 +128,7 @@ fn lock(path: &Path) -> Result<File> {
.context("session memory worker is busy; retry after it finishes")?;
Ok(file)
}
-fn loopback(url: &str) -> Result<()> {
+pub(super) fn loopback(url: &str) -> Result<()> {
let url = reqwest::Url::parse(url)?;
ensure!(
matches!(url.scheme(), "http" | "https")
@@ -164,7 +164,7 @@ fn config(project: &Path) -> Result<Config> {
);
Ok(config)
}
-fn quote(text: &str) -> String {
+pub(super) fn quote(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\\''"))
}
fn hooks(project: &Path, binary: &Path) -> Result<Value> {
diff --git a/engine/crates/xerj-rerank/tests/egress_inventory.rs b/engine/crates/xerj-rerank/tests/egress_inventory.rs
index 5226847aa..8ac6b6836 100644
--- a/engine/crates/xerj-rerank/tests/egress_inventory.rs
+++ b/engine/crates/xerj-rerank/tests/egress_inventory.rs
@@ -92,6 +92,10 @@ const KNOWN: &[(&str, Role)] = &[
"xerj-autoindex/src/session_memory.rs",
Role::Client("`xerj sessions hook`"),
),
+ (
+ "xerj-autoindex/src/search_hints.rs",
+ Role::Client("`xerj init hook`"),
+ ),
// Batch retrieval uses the same operator-selected node URL and auth as
// `xerj mcp` (localhost:9200 by default). It sends queries to /_msearch
// and optionally reads mappings; it adds no node-side egress path.
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index f7451d440..fca366702 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -3120,6 +3120,12 @@ fn main() -> Result<()> {
let rt = build_runtime(2)?;
std::process::exit(rt.block_on(xerj_mcp::run_batch_cli(&args)));
}
+ if matches!(xerj_common::argv::subcommand().as_deref(), Some("init")) {
+ let args = xerj_common::argv::args_after_subcommand();
+ if args.first().is_some_and(|a| a == "hook") {
+ std::process::exit(xerj_autoindex::search_hints::run(&args[1..]));
+ }
+ }
if matches!(xerj_common::argv::subcommand().as_deref(), Some("sessions")) {
let args = xerj_common::argv::args_after_subcommand();
std::process::exit(xerj_autoindex::sessions::run_cli(&args));
diff --git a/tools/search-hints/README.md b/tools/search-hints/README.md
new file mode 100644
index 000000000..a37887099
--- /dev/null
+++ b/tools/search-hints/README.md
@@ -0,0 +1,101 @@
+# Advisory search hints for Claude Code
+
+Opt in from the project directory (macOS/Linux):
+
+```sh
+xerj init --hooks --dry-run
+xerj init --hooks
+```
+
+Success: init prints `enabled Claude Code search hints`. Review the new
+`PreToolUse` group in `.claude/settings.json`, then restart Claude Code. Ordinary
+init does not install it. This feature is separate from `xerj init --memory`;
+configure/remove the two features in separate invocations.
+
+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.
+The suggestion includes the prefix and shell-quoted node URL; it does not search, index or start a node.
+Subdirectories and additional directories abstain rather than guess the scope.
+
+On `Grep`, `Glob`, or the third `Read` in a session, the hook may return one
+line of `PreToolUse.additionalContext`. It never returns a permission decision
+or replacement input; the host retains its normal permission flow and tool call.
+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.
+
+`--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
+lookup supplies auth. No key is stored. Proxies and redirects are disabled.
+An eligible invocation makes one read-only catalog search with a 100 ms connect
+and 300 ms request timeout and a 256 KiB response cap; the installed command
+has a two-second host timeout. Startup, key discovery and filesystem work are
+outside the HTTP timeout; no laptop-wide latency claim is made.
+
+There is no hint on a failed/partial/truncated catalog read, over 200 run
+records, ambiguous latest root ownership, unsupported prefix spelling, wrong
+host event/cwd, corrupt state, busy lock or offline/unauthorized node. Prefixes
+are lowercase ASCII letters/digits, hyphens/underscores, at most 128 bytes.
+The catalog is evidence of a prior run, not a freshness check against files or
+manually deleted indices. Tool input, search patterns, transcript paths and raw
+session IDs are neither stored nor sent. Only catalog metadata and runtime
+authentication go to the node; local counters retain SHA-256 session hashes.
+
+## Remove, recover, upgrade
+
+```sh
+xerj init --hooks --remove --dry-run
+xerj init --hooks --remove
+```
+
+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
+folder may be deleted manually; it contains no indexed documents. Installing
+again enables the hook. Re-run init after moving/upgrading the binary: the old
+owned group is replaced with the new absolute, shell-quoted executable path.
+
+Malformed settings, edited/duplicated/missing managed groups and unowned exact
+matches refuse setup/removal without rewriting settings. Restore just the owned
+`group` from `.claude/xerj-hints/config.json` into the PreToolUse array (once),
+then retry removal. If settings were copied without config.json, manually remove
+only the reviewed obsolete group before reinstalling; init never adopts it. Backups `settings-<digest>.bak` contain exact prior settings;
+compare them before manually restoring to preserve intervening user edits.
+A busy lock means retry when the other installer/hook finishes. Corrupt counters
+can be moved aside to reset rate limits. Setup refuses symlinks and requires the
+private state directory to be owned by the current user with mode 0700.
+
+Settings/config are individually atomically replaced, not a multi-file crash
+transaction. A settings publication error rolls config back; a power loss
+between publications may require the manual owned-group recovery above. The
+file checks defend ordinary misconfiguration/symlinks, not a hostile same-user
+process racing every filesystem operation. Settings are project-controlled
+executable hook configuration: enable only in a trusted workspace.
+
+## Reproduce
+
+```sh
+python3 tools/search-hints/smoke.py --binary engine/target/release/xerj
+python3 tools/search-hints/smoke.py --binary engine/target/release/xerj --authenticated
+```
+
+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
+to four turns, and deliberately asks the agent to follow a delivered hint.
+
+The default smoke commands use only a private node and a tiny synthetic Rust project; they do not
+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).
+
+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.
diff --git a/tools/search-hints/VERIFICATION.md b/tools/search-hints/VERIFICATION.md
new file mode 100644
index 000000000..c879c7d50
--- /dev/null
+++ b/tools/search-hints/VERIFICATION.md
@@ -0,0 +1,174 @@
+# Search hint verification — 2026-11-02
+
+Written and executed by OpenAI Codex, operated by @Jarvis636431, on macOS arm64
+with Rust 1.97.1. Independent branch based on upstream `9422d0f53`; builds on
+already-merged session hooks (#2849), not an unmerged prerequisite. The diff
+contains no Cargo dependency/lockfile, node API, storage, workflow or MCP schema
+change. The candidate is source-built rc.100, not a published-release claim.
+
+## Failing controls and regression coverage
+
+Before implementation, the new init flag regression failed on `--hooks`
+(`search_hints_are_an_explicit_separate_opt_in`: 0 passed, 1 failed).
+It passes after implementation. The existing ordinary-init and session-memory
+tests remain; none was weakened.
+
+A temporary mutation from `INTERVAL = 10` to `INTERVAL = 0` failed the persistent
+rate-limit test at `assertion failed: fire(p.path(), "a", "Grep").is_none()`.
+Restored the source before final checks. An earlier mutation attempt failed
+in the linker because the disk was full; that attempt is not defect evidence.
+
+The HTTP regression first failed its `redirect` assertion: reqwest's
+`error_for_status` does not reject 302, even with redirects disabled. Added an
+explicit success-status check; the same regression now passes. Near-limit
+settings are refused before publishing a configuration that could not be read
+back. Settings-publication failure is injected after config publication: exact
+old settings/config bytes survive, the hook still works, and removal succeeds
+on retry.
+
+Coverage lives in `engine/crates/xerj-autoindex/src/search_hints/tests.rs`:
+configuration dry-run/merge/idempotence/binary-path update, exact ownership,
+foreign and memory hooks preserved, malformed/edited/duplicated settings,
+restore-and-remove recovery, failed publication rollback, read and response
+budgets, disabled/busy/corrupt state, session isolation, bounded session FIFO,
+third Read and ten-call spacing, catalog latest-root ownership, truncated and
+ambiguous metadata, unsafe prefixes, wrong host events/cwd, HTTP/3xx handling,
+no tool input in the request, and remote/symlink refusal.
+
+## Commands
+
+From `engine/` (loopback/process permission allowed for tests):
+
+```sh
+PATH="/usr/bin:/bin:/usr/sbin:/sbin:$PATH" GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 CARGO_INCREMENTAL=0 TMPDIR=/private/tmp cargo test --locked --offline -p xerj-autoindex -- --test-threads=2 --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 cargo test --locked --offline -p xerj-rerank
+cargo clippy --locked --offline -p xerj-autoindex --all-targets -- -D warnings -A dead_code
+cargo fmt --all -- --check
+cargo build --locked --offline --release -j 32 -p xerj-autoindex
+cargo build --locked --offline --profile ci-test -j 8 -p xerj-server -p es-yaml-runner
+```
+
+The three explicit filters are the previously documented macOS filename cases
+in [session-import verification](../session-import/VERIFICATION.md); the changed
+code does not touch those paths. The `dead_code` allowance is for existing
+`content::resolve_reporting`. Shipping server fat-LTO linking was stopped on an
+earlier snapshot; no completed shipping-server release build is claimed. The
+changed crate has its own scoped release build; live tests use `ci-test` nodes.
+A stale build-script cache pointed at an old deleted worktree; touching only
+`xerj-server/build.rs`'s timestamp regenerated it (no source diff). Build-cache
+cleanup retained source/data and did not use `cargo clean`.
+
+From the repository root:
+
+```sh
+python3 tools/search-hints/smoke.py --binary engine/target/ci-test/xerj
+python3 tools/search-hints/smoke.py --binary engine/target/ci-test/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 smoke harness copies the binary to an immutable, privately owned path
+containing an apostrophe and space, hashes that copy, and actually invokes it.
+It uses a fresh loopback node, generated config, a 99% disk flood watermark to
+admit the tiny fixture on this shared disk, a two-core resource setting and the
+default lexical mode. Only this temporary node/data and owned `hint-smoke`
+corpus are touched. Authentication mode passes a fresh runtime `XERJ_AUTH` / `XERJ_API_KEY`;
+this does not independently verify automatic key discovery.
+
+## Contribution review and boundaries
+
+Audited against `docs/CONTRIBUTION_REVIEW.md`: effective diff/ancestry,
+project ownership, preflight ordering, independent rate state, bounded reads,
+publication failure and recovery, output routing, read-only HTTP, platform
+conditions, metadata ambiguity, auth origin and egress inventory. The existing
+session-memory primitives change only visibility, not behavior. The host format
+is from the official Claude Code hook reference; fs2's MIT/Apache-2.0 nonblocking
+lock behavior and in-tree catalog cohort logic are cited in README.md. No peer
+implementation was copied.
+
+The local config/counters are version 1 and session IDs are hashed. FIFO eviction
+resets the oldest session's quota; no unbounded per-session file growth. Setup
+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
+recovery were not tested. The catalog cap intentionally abstains beyond 200 run
+records. No model, ANN, performance, relevance or spontaneous adoption claim.
+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.
+
+## Final executable and workflow receipts
+
+The final immutable executable copies used by both smoke modes and the fresh
+conformance node have SHA-256
+`db649d8a45335f5c54bf2ffc0d967008e621a06877b39d6c4c910a291d874c12`.
+
+Both smoke modes passed **26 installed hook invocations each**, every one exit
+0 with empty stderr. Fresh/unchanged setup, ordinary init, foreign settings and
+session-memory coexistence, malformed/oversized/wrong-event input, offline and
+unindexed silence, third Read, quota, independent sessions, autoindex map, cited
+local definition lookup, graceful node restart, owned corpus removal, edited
+group refusal/restoration, uninstall and reinstall passed. Both private nodes
+in each mode stopped with exit 0. The fixture had **2 files / 1.4 KB / 3 records**;
+actual indexing walls were **1.7 s** (non-authenticated host sample) and **1.6 s**
+(authenticated). These are fixture receipts, not throughput benchmarks.
+
+### Controlled actual-host before/after
+
+```sh
+python3 tools/search-hints/smoke.py --binary engine/target/ci-test/xerj --claude-sample --receipt NEW.json
+```
+
+Claude Code **2.1.278**, two non-interactive sessions, each capped at four turns,
+project-only settings and no persisted host session. The same prompt explicitly
+asks for Grep first and an XERJ search *if a hook suggests it*. Baseline with
+only our hook group removed: tool list `[Grep]`, **0 XERJ search calls**. Enabled:
+`[Grep, Bash]`, **1 XERJ search call**. Both host commands exited 0 with no result
+error. [host-sample.json](./host-sample.json) is the actual normalized receipt;
+raw transcripts, session IDs and machine paths are not published. This proves
+controlled delivery/uptake, not spontaneous preference, search quality, or a
+statistically measured adoption improvement. Repeated Read and quota are covered
+by deterministic replay, not by additional model-generated sessions.
+
+One full-suite attempt on the URL-bearing final source hit an unrelated existing
+`xc::tests::corpus_add_partial_clone_failure_preserves_retry_and_names_the_context`
+failure: restoring the temporary offline origin returned `DirectoryNotEmpty`.
+The test passed immediately in isolation. Its cause was not established; the
+Git executable was `/usr/bin/git`, so no wrapper-caused diagnosis is claimed.
+The final full-suite rerun isolates global/system Git configuration as shown
+above, with the same three existing macOS filters and no source/test changes.
+
+Final complete crate run with isolated Git configuration: **2037 passed,
+0 failed, 5 existing ignored, 3 existing macOS filters**, across 12 test/doc
+summary groups. Final focused hook run: **11 passed, 0 failed**. Complete rerank
+run: **59 passed, 0 failed**, including the four outbound-inventory checks.
+Scoped autoindex release build, final `ci-test` node/runner build, Clippy with
+only the existing dead-code allowance, fmt/check, Python compilation, whitespace
+and workflow timeout guard passed. The final hint carries the configured node
+URL as well as prefix; the regression and both smoke modes assert it explicitly.
+
+Fresh-node ES-YAML on that same executable snapshot, using 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**, 233 files, runner exit 0. It retains
+**74 catch-lenient cases** under the existing suite policy. 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.
+
+### Last upstream composition
+
+After validation and implementation commit `7095b0147`, fetched upstream again
+and normally merged `50ea0bb58` (#2845). It changes the field-report HTTP function,
+its JavaScript tests/CI step and changelog only. The merge was clean, including
+the changelog. `git diff 7095b0147 -- engine` is empty: the entire Rust source and
+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.
diff --git a/tools/search-hints/host-sample.json b/tools/search-hints/host-sample.json
new file mode 100644
index 000000000..40fda7fc3
--- /dev/null
+++ b/tools/search-hints/host-sample.json
@@ -0,0 +1,21 @@
+{
+ "claude_version": "2.1.278 (Claude Code)",
+ "sample_kind": "engineered hint delivery/uptake check; not a relevance or adoption benchmark",
+ "baseline": {
+ "exit_code": 0,
+ "tool_names": [
+ "Grep"
+ ],
+ "xerj_search_calls": 0,
+ "result_error": false
+ },
+ "enabled": {
+ "exit_code": 0,
+ "tool_names": [
+ "Grep",
+ "Bash"
+ ],
+ "xerj_search_calls": 1,
+ "result_error": false
+ }
+}
diff --git a/tools/search-hints/smoke.py b/tools/search-hints/smoke.py
new file mode 100644
index 000000000..4a7bf57d4
--- /dev/null
+++ b/tools/search-hints/smoke.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python3
+"""Isolated real-node lifecycle and installed PreToolUse command verification."""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import socket
+import shutil
+import shlex
+import subprocess
+import tempfile
+import time
+from urllib.request import Request, build_opener, ProxyHandler
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--binary', required=True, type=Path)
+ parser.add_argument('--authenticated', action='store_true')
+ parser.add_argument('--claude-sample', action='store_true', help='run a controlled two-session real Claude Code delivery sample')
+ parser.add_argument('--receipt', type=Path, help='new JSON file for the controlled host sample summary')
+ args = parser.parse_args()
+ original = args.binary.resolve(strict=True)
+ env = {k: v for k, v in os.environ.items() if not k.startswith('XERJ_')
+ and k.lower() not in ('http_proxy', 'https_proxy', 'all_proxy', 'no_proxy')}
+ env.update(XERJ_DISABLE_FEEDBACK='true', XERJ_NUM_CPUS='2')
+ opener = build_opener(ProxyHandler({}))
+ with tempfile.TemporaryDirectory(prefix='xerj-search-hints-') as temp:
+ work = Path(temp).resolve()
+ binary = work / "xerj's binary"
+ shutil.copyfile(original, binary)
+ binary.chmod(0o700)
+ print('Executable SHA-256:', hashlib.sha256(binary.read_bytes()).hexdigest(), flush=True)
+ project = work / "project's work"
+ project.mkdir()
+ (project / 'src').mkdir()
+ (project / 'src/lib.rs').write_text('pub fn recover_snapshot() -> bool { true }\n')
+ sockets = [socket.socket(), socket.socket()]
+ for sock in sockets:
+ sock.bind(('127.0.0.1', 0))
+ port, rest = [sock.getsockname()[1] for sock in sockets]
+ for sock in sockets:
+ sock.close()
+ url = f'http://127.0.0.1:{port}'
+ env['XERJ_URL'] = url
+ node_config = work / 'node.toml'
+ node_config.write_text(f'[server]\nes_compat_port={port}\nrest_port={rest}\ngrpc_port=0\n'
+ f'data_dir={json.dumps(str(work / "data"))}\n'
+ '[limits]\ndisk_flood_stage_percent=99\n')
+ settings = project / '.claude/settings.json'
+ state = project / '.claude/xerj-hints'
+ node = None
+ logs = []
+ commands = 0
+
+ def cli(*args, expected=0):
+ result = subprocess.run([str(binary), *args], cwd=project, env=env,
+ text=True, capture_output=True, timeout=90)
+ assert result.returncode == expected, (args, result.stdout, result.stderr)
+ return result
+
+ def request(path):
+ headers = {}
+ if 'XERJ_AUTH' in env:
+ headers['Authorization'] = env['XERJ_AUTH']
+ with opener.open(Request(url + path, headers=headers), timeout=3) as response:
+ return json.load(response)
+
+ def start():
+ nonlocal node
+ log = open(work / f'node-{len(logs)}.log', 'w+')
+ logs.append(log)
+ command = [str(binary), '--config', str(node_config)]
+ if not args.authenticated:
+ command.append('--insecure')
+ node = subprocess.Popen(command, cwd=work, env=env, stdout=log, stderr=log)
+ deadline = time.monotonic() + 40
+ while time.monotonic() < deadline:
+ if node.poll() is not None:
+ log.seek(0)
+ raise AssertionError(log.read()[-3000:])
+ key = work / 'data/admin.key'
+ if args.authenticated and key.exists():
+ env['XERJ_API_KEY'] = key.read_text().strip()
+ env['XERJ_AUTH'] = 'ApiKey ' + env['XERJ_API_KEY']
+ try:
+ request('/')
+ return
+ except Exception:
+ time.sleep(.1)
+ raise AssertionError('private node readiness timeout')
+
+ def stop():
+ nonlocal node
+ if node is not None:
+ node.terminate()
+ try:
+ status = node.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ node.kill()
+ node.wait()
+ raise
+ node = None
+ assert status == 0, status
+ print('Private node graceful exit 0', flush=True)
+
+ def hook(tool='Grep', sid='sample', expect=False, payload=None, command=None):
+ nonlocal commands
+ if command is None:
+ command = json.loads(settings.read_text())['hooks']['PreToolUse'][-1]['hooks'][0]['command']
+ if payload is None:
+ payload = json.dumps({'hook_event_name': 'PreToolUse', 'cwd': str(project),
+ 'session_id': sid, 'tool_name': tool,
+ 'tool_input': {'pattern': 'PRIVATE_QUERY_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'] == 'PreToolUse', 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)
+ assert not settings.exists() and not state.exists()
+ settings.parent.mkdir(parents=True, exist_ok=True)
+ foreign = {'permissions': {'allow': ['Read']}, 'hooks': {'PreToolUse': [
+ {'matcher': 'UnrelatedTool', 'hooks': [{'type': 'command', 'command': 'echo foreign'}]}]}}
+ settings.write_text(json.dumps(foreign))
+ cli('init', '--hooks', '--url', url)
+ first = settings.read_bytes()
+ cli('init', '--hooks', '--url', url)
+ assert settings.read_bytes() == first
+ hook() # offline
+ start()
+ hook() # reachable, not indexed
+ if args.authenticated:
+ for path in [settings, state / 'config.json']:
+ assert env['XERJ_API_KEY'].encode() not in path.read_bytes()
+ # Demonstrate ordinary init and opt-in memory coexist without changing the hint group.
+ cli('init', '--url', url)
+ assert settings.read_bytes() == first
+ dry = cli('autoindex', str(project), '--dry-run', '--prefix', 'hint-smoke', '--url', url)
+ print(dry.stdout + dry.stderr, flush=True)
+ indexed = cli('autoindex', str(project), '--prefix', 'hint-smoke', '--state-dir', str(work / 'journal'),
+ '--url', url, '--no-graph', '--yes')
+ print(indexed.stdout + indexed.stderr, flush=True)
+ assert 'xerj-done ok=true' in indexed.stdout + indexed.stderr
+ if args.claude_sample:
+ prompt = ("This is an isolated hook delivery test. First use Grep once to find "
+ "recover_snapshot in src/. If a hook supplies an XERJ search hint, "
+ "follow it with exactly one xerj search via Bash, using this executable: "
+ + shlex.quote(str(binary)) + ". Otherwise answer from Grep. Give the definition's "
+ "file and line. Do not edit files, index anything, or submit feedback.")
+ summary = {'claude_version': subprocess.check_output(['claude', '--version'], text=True).strip(),
+ 'sample_kind': 'engineered hint delivery/uptake check; not a relevance or adoption benchmark'}
+ for enabled in [False, True]:
+ config = json.loads(first)
+ if not enabled:
+ config['hooks']['PreToolUse'] = config['hooks']['PreToolUse'][:-1]
+ settings.write_text(json.dumps(config))
+ host = subprocess.run(['claude', '-p', prompt, '--output-format', 'stream-json', '--verbose',
+ '--max-turns', '4', '--no-session-persistence', '--setting-sources', 'project',
+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
+ '--tools', 'Grep,Glob,Read,Bash', '--allowedTools', 'Grep,Glob,Read,Bash'],
+ cwd=project, env=env, text=True, capture_output=True, timeout=90)
+ events = [json.loads(line) for line in host.stdout.splitlines() if line.startswith('{')]
+ calls = {block['id']: block for event in events for block in event.get('message', {}).get('content', [])
+ if isinstance(block, dict) and block.get('type') == 'tool_use'}
+ names = [block['name'] for block in calls.values()]
+ searches = sum(block.get('name') == 'Bash' and 'search' in block.get('input', {}).get('command', '')
+ and 'xerj' in block.get('input', {}).get('command', '') for block in calls.values())
+ result = {'exit_code': host.returncode, 'tool_names': names, 'xerj_search_calls': searches,
+ 'result_error': any(event.get('is_error', False) for event in events)}
+ summary['enabled' if enabled else 'baseline'] = result
+ print('Claude Code controlled sample:', enabled, json.dumps(result), flush=True)
+ assert host.returncode == 0 and not result['result_error'] and 'Grep' in names, result
+ assert searches == int(enabled), result
+ settings.write_bytes(first)
+ if args.receipt:
+ with args.receipt.open('x') as out:
+ json.dump(summary, out, indent=2)
+ out.write('\n')
+ cli('init', '--memory', '--url', url)
+ memory = (project / '.claude/settings.local.json').read_bytes()
+ mapped = cli('autoindex', 'map', '--prefix', 'hint-smoke', '--url', url)
+ assert 'hint-smoke' in mapped.stdout, mapped
+ # Controlled replay: Read x3, Grep x9, Glob; no actual agent/model is simulated.
+ hook('Read', sid='reads')
+ hook('Read', sid='reads')
+ hook('Read', sid='reads', expect=True)
+ for _ in range(9):
+ hook('Grep', sid='reads')
+ hook('Glob', sid='reads', expect=True)
+ hook(sid='independent', expect=True)
+ hook(payload='{broken')
+ hook(payload='x' * 65537)
+ for field, value in [('tool_name', 'Bash'), ('hook_event_name', 'PostToolUse'), ('cwd', str(work))]:
+ event = {'hook_event_name': 'PreToolUse', 'cwd': str(project), 'session_id': 'wrong', 'tool_name': 'Grep'}
+ event[field] = value
+ hook(payload=json.dumps(event))
+ counters = (state / 'counters.json').read_text()
+ assert 'PRIVATE_QUERY_DO_NOT_STORE' not in counters and 'independent' not in counters
+ found = cli('def', 'recover_snapshot', '--prefix', 'hint-smoke', '--url', url)
+ assert 'recover_snapshot' in found.stdout and 'lib.rs' in found.stdout, found
+ stop()
+ hook(sid='offline')
+ start()
+ hook(sid='reads') # rate counter survives node restart
+ hook(sid='restarted', expect=True)
+ cli('autoindex', 'remove', '--prefix', 'hint-smoke', '--root', str(project), '--url', url, '--yes')
+ hook(sid='removed-corpus')
+ saved = json.loads(settings.read_text())
+ owned = saved['hooks']['PreToolUse'][-1]
+ saved['hooks']['PreToolUse'][-1]['matcher'] = 'Bash'
+ settings.write_text(json.dumps(saved))
+ edited = settings.read_bytes()
+ cli('init', '--hooks', '--remove', '--url', url, expected=1)
+ assert settings.read_bytes() == edited
+ # Restore uniquely owned group from the persisted config, then removal works.
+ saved['hooks']['PreToolUse'][-1] = json.loads((state / 'config.json').read_text())['group']
+ settings.write_text(json.dumps(saved))
+ command = owned['hooks'][0]['command']
+ cli('init', '--hooks', '--remove', '--url', url)
+ assert json.loads(settings.read_text()) == foreign
+ hook(command=command)
+ 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)
+ finally:
+ stop()
+ for log in logs:
+ log.close()
+
+
+if __name__ == '__main__':
+ main()