Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(hooks): route Hermes tool events by their workdir/path, keep source exclusions binding

AkitaOnRailsc97766ea18fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2cda636..600920c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- Fixed Hermes Agent tool events being dropped under `capture_mode =
+ allowlist`. Hermes reports its own process directory (usually `~`) as the
+ payload `cwd` and points each tool at a repository with an absolute
+ `workdir` or `path`, so the marker lookup never found the repository's
+ `.ai-memory.toml`. The native `ai-memory hook` now also routes a shell
+ command by its absolute `workdir` and a search/list tool by its absolute
+ `path`, alongside the file-tool targets it already followed, when that
+ location proves one other repository or marker; relative locations still
+ keep the payload `cwd`. A reroute is now refused when the payload `cwd`'s own
+ `[capture] ignore_paths` would drop the event, so an exclusion that names a
+ path outside its checkout, or a source file read by a command whose
+ `workdir` points at another project, is no longer judged only by the
+ destination's policy. (#1199)
+
## [2.6.3] - 2026-10-09
### Fixed
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 9d8d4df4..1f7413ef 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -20,7 +20,7 @@ use std::time::Duration;
use ai_memory_core::{AgentKind, ManagedRunId, SessionId};
use ai_memory_hooks::capture_policy::metadata_only_body;
use ai_memory_hooks::{
- CaptureDisposition, CaptureMode, HookEvent, PolicyState, absolute_file_tool_paths,
+ CaptureDisposition, CaptureMode, HookEvent, PolicyState, absolute_tool_location_paths,
repository_admits_capture,
};
use ai_memory_llm::OidcToken;
@@ -728,18 +728,19 @@ where
}
let (payload_cwd, canonical_session_id) = hook_context(&args.agent, &json);
let tool_event = is_tool_event(&args.event);
- // Some harnesses keep a subagent's parent cwd in every payload even when
- // a file tool operates in another checkout (#932). A recognized absolute
- // target may select that checkout, but only when every path proves the
- // same repository/marker boundary. This must precede capture policy and
+ // Some harnesses report a cwd other than where the tool ran: a subagent's
+ // parent session (#932), or Hermes' own process cwd while its tools take
+ // a per-call `workdir`/`path` (#1199). A recognized absolute location may
+ // select that checkout, but only when every path proves the same
+ // repository/marker boundary. This must precede capture policy and
// server-profile resolution so the destination's privacy and credentials
// remain authoritative.
- let file_routing_cwd = payload_cwd.as_deref().and_then(|cwd| {
+ let tool_routing_cwd = payload_cwd.as_deref().and_then(|cwd| {
tool_event
- .then(|| file_tool_routing_cwd(agent_kind, &json, cwd))
+ .then(|| tool_location_routing_cwd(agent_kind, &json, cwd))
.flatten()
});
- if let Some(cwd) = file_routing_cwd.as_deref()
+ if let Some(cwd) = tool_routing_cwd.as_deref()
&& let Some(object) = json.as_object_mut()
{
// `HookEnvelope` deliberately gives the native body cwd precedence
@@ -748,7 +749,7 @@ where
object.insert("cwd".into(), cwd.into());
payload = serde_json::to_string(&json)?;
}
- let policy_cwd = file_routing_cwd.or(payload_cwd);
+ let policy_cwd = tool_routing_cwd.or(payload_cwd);
let inspection_cwd = policy_cwd.as_deref().map(lexical_capture_cwd);
let policy = policy_cwd.as_deref().map(capture_policy);
let decision = policy.as_ref().filter(|_| tool_event).map(|policy| {
@@ -1254,14 +1255,23 @@ fn file_route_anchor(cwd: &Path) -> FileRouteAnchor {
}
}
-/// Pick a destination cwd only when absolute file-tool paths prove a single
-/// repository/marker boundary different from the payload cwd.
-fn file_tool_routing_cwd(
+/// Pick a destination cwd only when a tool call's absolute location (file
+/// targets, a search directory, a shell `workdir`) proves a single
+/// repository/marker boundary different from the payload cwd, and the payload
+/// cwd's own capture policy would keep the event.
+///
+/// The second condition keeps a reroute from escaping the source's
+/// `ignore_paths`: patterns may name paths outside the source checkout
+/// (`~/vault/**`, an absolute path), and a shell command's arguments may name
+/// source files while its `workdir` points elsewhere. Without a reroute the
+/// event stays with the payload cwd, whose policy then drops it exactly as it
+/// would have before any rerouting existed.
+fn tool_location_routing_cwd(
agent: AgentKind,
raw: &serde_json::Value,
payload_cwd: &str,
) -> Option<String> {
- let paths = absolute_file_tool_paths(agent, raw, payload_cwd)?;
+ let paths = absolute_tool_location_paths(agent, raw, payload_cwd)?;
let source_dir = existing_target_dir(Path::new(payload_cwd))?;
let source_anchor = file_route_anchor(&source_dir);
let mut selected: Option<(FileRouteAnchor, PathBuf)> = None;
@@ -1280,7 +1290,15 @@ fn file_tool_routing_cwd(
}
}
let (target_anchor, dir) = selected?;
- (target_anchor != source_anchor).then(|| dir.to_string_lossy().into_owned())
+ if target_anchor == source_anchor {
+ return None;
+ }
+ let source_keeps = capture_policy(payload_cwd)
+ .inspect(agent, raw, &lexical_capture_cwd(payload_cwd))
+ .protocol()
+ .disposition()
+ == CaptureDisposition::Keep;
+ source_keeps.then(|| dir.to_string_lossy().into_owned())
}
/// Where one event is delivered (#992).
@@ -2755,7 +2773,7 @@ mod tests {
"tool_input": {"file_path": "../destination/file.txt"}
});
assert_eq!(
- file_tool_routing_cwd(AgentKind::ClaudeCode, &relative, cwd),
+ tool_location_routing_cwd(AgentKind::ClaudeCode, &relative, cwd),
None,
"a relative path cannot independently prove a destination"
);
@@ -2767,7 +2785,7 @@ mod tests {
"tool_input": {"file_path": external_dir.join("file.txt")}
});
assert_eq!(
- file_tool_routing_cwd(AgentKind::ClaudeCode, &external, cwd),
+ tool_location_routing_cwd(AgentKind::ClaudeCode, &external, cwd),
None,
"an arbitrary absolute path must not mint a project"
);
@@ -2780,12 +2798,240 @@ mod tests {
]}
});
assert_eq!(
- file_tool_routing_cwd(AgentKind::ClaudeCode, &mixed, cwd),
+ tool_location_routing_cwd(AgentKind::ClaudeCode, &mixed, cwd),
None,
"one event cannot be attributed to two projects"
);
}
+ /// Spool one native hook event and return what reached the spool.
+ async fn spool_one(
+ data_dir: &Path,
+ agent: &str,
+ capture_mode: Option<crate::cli::CaptureModeArg>,
+ raw: &serde_json::Value,
+ ) -> Vec<hook_spool::SpoolEntry> {
+ let mut args = devin_hook_args("post-tool-use");
+ args.agent = agent.into();
+ args.capture_mode = capture_mode;
+ run_with_payload(
+ Some(data_dir.to_path_buf()),
+ args,
+ raw.to_string(),
+ &mut Vec::new(),
+ |_, _| panic!("a tool event below the threshold must only spool"),
+ )
+ .await
+ .unwrap();
+ let spool = hook_spool::spool_dir(data_dir);
+ if spool.exists() {
+ read_spooled_entries(&spool)
+ } else {
+ Vec::new()
+ }
+ }
+
+ /// Hermes reports its own process cwd (usually `~`) on every tool event and
+ /// points each call at a repository through `workdir` or `path` (#1199).
+ /// Under allowlist mode the process cwd has no marker, so the tool's own
+ /// absolute location must find the repository's marker.
+ #[tokio::test]
+ async fn hermes_tool_location_finds_the_marker_the_process_cwd_lacks() {
+ let tmp = tempfile::tempdir().unwrap();
+ let home = tmp.path().join("home");
+ let repo = home.join("dev/some-repo");
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "workspace = \"w\"\nproject = \"some-repo\"\n",
+ )
+ .unwrap();
+ let allowlist = Some(crate::cli::CaptureModeArg::Allowlist);
+ let event = |tool: &str, input: serde_json::Value| {
+ serde_json::json!({
+ "hook_event_name": "post_tool_call",
+ "tool_name": tool,
+ "tool_input": input,
+ "session_id": "hermes-session",
+ "cwd": home,
+ "extra": {"tool_call_id": "call-1", "status": "ok"}
+ })
+ };
+
+ for (name, raw) in [
+ (
+ "terminal workdir",
+ event(
+ "terminal",
+ serde_json::json!({"command": "git status", "workdir": repo}),
+ ),
+ ),
+ (
+ "file path",
+ event(
+ "read_file",
+ serde_json::json!({"path": repo.join("README.md")}),
+ ),
+ ),
+ (
+ "search directory",
+ event(
+ "search_files",
+ serde_json::json!({"pattern": "fn", "path": repo}),
+ ),
+ ),
+ ] {
+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));
+ let entries = spool_one(&data_dir, "hermes", allowlist, &raw).await;
+ assert_eq!(entries.len(), 1, "{name}");
+ assert_eq!(
+ query_param(&entries[0].url, "project"),
+ Some("some-repo"),
+ "{name}"
+ );
+ let body: serde_json::Value = serde_json::from_str(&entries[0].body).unwrap();
+ assert_eq!(body["cwd"], repo.to_string_lossy().as_ref(), "{name}");
+ }
+
+ // Controls: a command with no location, or a relative one Hermes
+ // resolves against a session cwd the payload never carries, still
+ // belongs to the unmarked process cwd and is not captured.
+ for (name, raw) in [
+ (
+ "no workdir",
+ event("terminal", serde_json::json!({"command": "git status"})),
+ ),
+ (
+ "relative workdir",
+ event(
+ "terminal",
+ serde_json::json!({"command": "git status", "workdir": "dev/some-repo"}),
+ ),
+ ),
+ (
+ "relative search",
+ event(
+ "search_files",
+ serde_json::json!({"pattern": "fn", "path": "."}),
+ ),
+ ),
+ ] {
+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));
+ assert!(
+ spool_one(&data_dir, "hermes", allowlist, &raw)
+ .await
+ .is_empty(),
+ "{name}"
+ );
+ }
+ }
+
+ /// A shell `workdir` reroute lands under the destination's exclusions: a
+ /// command reading an ignored path there is dropped, a public one is kept.
+ #[tokio::test]
+ async fn workdir_reroute_applies_the_destination_capture_policy() {
+ let tmp = tempfile::tempdir().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("repo");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "project = \"repo\"\n[capture]\nignore_paths = [\"secret/**\"]\n",
+ )
+ .unwrap();
+ for (command, spooled) in [("cat secret/token.txt", 0), ("cat README.md", 1)] {
+ let raw = serde_json::json!({
+ "tool_name": "terminal",
+ "tool_input": {"command": command, "workdir": repo},
+ "tool_response": "SENTINEL_CONTENT",
+ "session_id": "hermes-session",
+ "cwd": home,
+ });
+ let data_dir = tmp.path().join(format!("data-{spooled}"));
+ assert_eq!(
+ spool_one(&data_dir, "hermes", None, &raw).await.len(),
+ spooled,
+ "{command}"
+ );
+ }
+ }
+
+ /// Adversarial: a reroute must never escape the payload cwd's own
+ /// `ignore_paths`. The source excludes a path outside its checkout and a
+ /// path inside it; a file tool targeting the first, or a shell command
+ /// naming the second while its `workdir` points at another project, would
+ /// otherwise be judged only by the destination's (inactive) policy and
+ /// spooled. Controls: the same tools on public paths still reroute.
+ #[tokio::test]
+ async fn a_reroute_cannot_escape_the_source_capture_exclusions() {
+ let tmp = tempfile::tempdir().unwrap();
+ let source = tmp.path().join("source");
+ let vault = tmp.path().join("vault");
+ let other = tmp.path().join("other");
+ for dir in [&source, &vault, &other] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ std::fs::write(
+ source.join(".ai-memory.toml"),
+ format!(
+ "project = \"source\"\n[capture]\nignore_paths = [\"secret/**\", {:?}]\n",
+ format!("{}/**", vault.display())
+ ),
+ )
+ .unwrap();
+ std::fs::write(vault.join(".ai-memory.toml"), "project = \"vault\"\n").unwrap();
+ std::fs::write(other.join(".ai-memory.toml"), "project = \"other\"\n").unwrap();
+ let bash = |command: String| {
+ serde_json::json!({
+ "session_id": "escape",
+ "cwd": source,
+ "tool_name": "Bash",
+ "tool_input": {"command": command, "workdir": other},
+ "tool_response": {"stdout": "SENTINEL_MUST_NOT_BE_SPOOLED"}
+ })
+ };
+ let read = |path: PathBuf| {
+ serde_json::json!({
+ "session_id": "escape",
+ "cwd": source,
+ "tool_name": "Read",
+ "tool_input": {"file_path": path},
+ "tool_response": {"content": "SENTINEL_MUST_NOT_BE_SPOOLED"}
+ })
+ };
+
+ for (name, raw) in [
+ ("file outside the source", read(vault.join("key.md"))),
+ (
+ "shell naming a source file",
+ bash(format!("cat {}", source.join("secret/token.txt").display())),
+ ),
+ ] {
+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));
+ assert!(
+ spool_one(&data_dir, "claude-code", None, &raw)
+ .await
+ .is_empty(),
+ "{name}: the source exclusion must still drop the event"
+ );
+ }
+
+ for (name, raw, project) in [
+ ("public file", read(other.join("readme.md")), "other"),
+ ("public shell", bash("git status".to_owned()), "other"),
+ ] {
+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));
+ let entries = spool_one(&data_dir, "claude-code", None, &raw).await;
+ assert_eq!(entries.len(), 1, "{name}");
+ assert_eq!(
+ query_param(&entries[0].url, "project"),
+ Some(project),
+ "{name}"
+ );
+ }
+ }
+
#[tokio::test]
async fn shell_command_reading_an_ignored_path_is_dropped_before_spool() {
for (command, spooled) in [("cat ./secret/*.md | head", 0), ("cat public/readme.md", 1)] {
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 33ee8132..5b44a383 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -733,6 +733,10 @@ struct Extracted<'a> {
/// `web_search` is non-file but runs nothing.
shell: bool,
workdir: Option<String>,
+ /// A search/list tool's explicit directory or file argument. Used only to
+ /// locate where the tool ran; capture policy drops search output under an
+ /// active marker regardless of it.
+ search_paths: Option<Vec<String>>,
call_id: Option<String>,
state: ExtractionState,
}
@@ -797,6 +801,9 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {
let command = (family == ToolFamily::NonFile)
.then(|| args.and_then(shell_command))
.flatten();
+ let search_paths = (family == ToolFamily::SearchList)
+ .then(|| args.and_then(|value| direct_paths(value.as_object()?)))
+ .flatten();
// OpenCode `bash`, OpenClaw `exec` and Codex `shell` run in `workdir`
// when given, so relative arguments resolve from there.
let shell = family == ToolFamily::NonFile && !name.eq_ignore_ascii_case("web_search");
@@ -833,6 +840,7 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {
command,
shell,
workdir,
+ search_paths,
call_id,
state,
}
@@ -943,22 +951,33 @@ fn extract_paths(name: &str, args: &Value) -> Option<Vec<String>> {
.then_some(paths)
}
-/// Return the bounded, normalized absolute paths named by a recognized file
-/// tool call, in the path's own separator style.
+/// Return the bounded, normalized absolute paths that locate where a
+/// recognized tool call ran, in the path's own separator style: a file tool's
+/// targets, a search/list tool's explicit directory, or a shell command's
+/// `workdir`.
///
-/// Native hook clients use this only to notice a file operation that targets
-/// another checkout while the harness keeps reporting the parent session's
-/// cwd. Relative paths are intentionally excluded: joining them to any cwd
-/// other than the payload's would be ambiguous, and they cannot independently
-/// prove a cross-project target. Unknown schemas and mixed/oversized inputs
-/// fail closed with `None`, matching capture-policy extraction.
+/// Native hook clients use this only to notice a tool call that operates in
+/// another checkout while the harness keeps reporting a different cwd — a
+/// subagent's parent session (#932), or Hermes' process cwd (#1199).
+/// Relative paths are intentionally excluded: joining them to any cwd other
+/// than the payload's would be ambiguous, and they cannot independently prove
+/// a cross-project target. Free-form command text is never parsed for a
+/// location; only the structured `workdir` field counts. Unknown schemas and
+/// mixed/oversized inputs fail closed with `None`, matching capture-policy
+/// extraction.
#[must_use]
-pub fn absolute_file_tool_paths(agent: AgentKind, raw: &Value, cwd: &str) -> Option<Vec<String>> {
+pub fn absolute_tool_location_paths(
+ agent: AgentKind,
+ raw: &Value,
+ cwd: &str,
+) -> Option<Vec<String>> {
let extracted = extract(agent, raw);
- if extracted.family != ToolFamily::File {
- return None;
- }
- let paths = extracted.paths?;
+ let paths = match extracted.family {
+ ToolFamily::File => extracted.paths?,
+ ToolFamily::SearchList => extracted.search_paths?,
+ ToolFamily::NonFile => vec![extracted.workdir?],
+ ToolFamily::Unknown => return None,
+ };
paths
.iter()
.map(|path| {
@@ -1448,7 +1467,7 @@ mod tests {
/// still collapsed; a POSIX target is unchanged. Windows CI caught the
/// forward-slash `C:/…` form being sent as the destination cwd.
#[test]
- fn absolute_file_tool_paths_keep_the_native_separator_style() {
+ fn absolute_tool_location_paths_keep_the_native_separator_style() {
let edit = |path: &str| {
serde_json::json!({
"tool_name": "Edit",
@@ -1456,7 +1475,7 @@ mod tests {
})
};
assert_eq!(
- absolute_file_tool_paths(
+ absolute_tool_location_paths(
AgentKind::ClaudeCode,
&edit(r"C:\work\destination\sub\..\a.txt"),
r"C:\work\source",
@@ -1464,7 +1483,7 @@ mod tests {
Some(vec![r"C:\work\destination\a.txt".to_owned()])
);
assert_eq!(
- absolute_file_tool_paths(
+ absolute_tool_location_paths(
AgentKind::ClaudeCode,
&edit("/work/destination/sub/../a.txt"),
"/work/source",
@@ -1473,6 +1492,60 @@ mod tests {
);
}
+ /// A tool's location is its file targets, a search tool's explicit
+ /// directory, or a shell command's structured `workdir` — absolute only,
+ /// and never a path parsed out of the command text (#1199).
+ #[test]
+ fn absolute_tool_location_paths_cover_search_dirs_and_shell_workdirs() {
+ let hermes = |tool: &str, input: Value| {
+ absolute_tool_location_paths(
+ AgentKind::Hermes,
+ &serde_json::json!({"tool_name": tool, "tool_input": input}),
+ "/home/user",
+ )
+ };
+ assert_eq!(
+ hermes(
+ "terminal",
+ serde_json::json!({"command": "ls", "workdir": "/work/repo/./src/.."})
+ ),
+ Some(vec!["/work/repo".to_owned()])
+ );
+ assert_eq!(
+ hermes(
+ "search_files",
+ serde_json::json!({"pattern": "x", "path": "/work/repo"})
+ ),
+ Some(vec!["/work/repo".to_owned()])
+ );
+ assert_eq!(
+ hermes("read_file", serde_json::json!({"path": "/work/repo/a.rs"})),
+ Some(vec!["/work/repo/a.rs".to_owned()])
+ );
+ for (tool, input) in [
+ (
+ "terminal",
+ serde_json::json!({"command": "ls", "workdir": "repo"}),
+ ),
+ (
+ "terminal",
+ serde_json::json!({"command": "cat /work/repo/a.rs"}),
+ ),
+ ("terminal", serde_json::json!({"workdir": "/work/repo"})),
+ (
+ "search_files",
+ serde_json::json!({"pattern": "x", "path": "."}),
+ ),
+ ("search_files", serde_json::json!({"pattern": "x"})),
+ (
+ "process",
+ serde_json::json!({"action": "list", "workdir": "/work/repo"}),
+ ),
+ ] {
+ assert_eq!(hermes(tool, input.clone()), None, "{tool} {input}");
+ }
+ }
+
#[test]
fn denylist_admits_every_repository() {
assert!(repository_admits_capture(CaptureMode::Denylist, false));
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 9383a252..017eb57c 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -47,7 +47,7 @@ pub use assistant_capture::{
pub use capture_policy::{
CaptureConfig, CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy,
CaptureProtocol, CaptureSource, ExtractionState, PolicyState, ToolFamily,
- absolute_file_tool_paths, describe_invalid_capture_config, repository_admits_capture,
+ absolute_tool_location_paths, describe_invalid_capture_config, repository_admits_capture,
};
pub use payload::{
HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 80c6038f..7ac302b2 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -293,12 +293,16 @@ normalises them to exactly one of these `ObservationKind` values:
| `other` | Unknown or unsupported hook event. |
Native hook clients correct one otherwise invisible cross-project case before
-spooling: if a recognized file-tool payload names only absolute paths in one
-other repository/marker boundary, that destination becomes the event cwd.
-Destination capture policy, server profile, and scope therefore travel
-together. Relative, mixed-project, unsupported, and non-project targets keep
-the harness cwd. Session identity and compiled-session ownership do not move;
-only the raw observations are attributed to the touched project (#932).
+spooling: if a recognized tool payload's absolute location (file-tool targets,
+a search/list tool's `path`, or a shell command's `workdir`) lies in one other
+repository/marker boundary, that destination becomes the event cwd.
+Destination capture policy, allowlist marker, server profile, and scope
+therefore travel together; the reroute is refused when the harness cwd's own
+capture policy would not keep the event, so the source's exclusions still
+apply. Relative, mixed-project, unsupported, and non-project targets keep the
+harness cwd. Session identity and compiled-session ownership do not move; only
+the raw observations are attributed to the touched project (#932, #1199 —
+Hermes reports its process cwd and locates each tool by `workdir`/`path`).
Antigravity CLI has no native SessionStart event. Its `PreInvocation` hook
fires before every model call, so the bridge maps only the documented
diff --git a/docs/install.md b/docs/install.md
index ecdb8252..c9047767 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1392,7 +1392,14 @@ the block and let Hermes accept it.
Two events are wired: `pre_tool_call` → `pre-tool-use` and `post_tool_call` →
`post-tool-use`. Their payload carries `tool_name` / `tool_input`, which is what
gives Hermes sessions tool observations, tool-family titles, and
-`[capture] ignore_paths` exclusion enforcement.
+`[capture] ignore_paths` exclusion enforcement. Hermes reports its own process
+directory (usually `~`) as the payload `cwd`, so the hook finds the project's
+`.ai-memory.toml` from each tool's absolute location instead: `terminal`'s
+`workdir`, a file tool's `path`, or `search_files`' `path`. A tool call with no
+absolute location (a relative `workdir`, the default `search_files` path)
+stays with the process directory and, under `capture_mode = allowlist`, is
+captured only if that directory carries a marker. See
+[marker-file.md](marker-file.md) for the routing rules.
Session lifecycle is deliberately not wired here: automatic recall, prompt
capture, session-end and the automatic handoff for Hermes belong to the memory
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 7c31abce..7c789a6b 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -849,16 +849,24 @@ Two guarantees hold in **both** modes:
Session-creating events are unaffected in both modes: opening a session in a
plain non-git folder still names the project after that folder.
-Some harnesses keep reporting the parent session's cwd when a subagent uses a
-file tool in another checkout. Native `ai-memory hook` commands compensate for
-that case before applying `follow-cwd` or `sticky`: a fixture-backed file-tool
-schema with absolute target paths is routed from the target when every path
-proves the same repository or marker boundary. The destination's capture
-policy and `server` profile are authoritative, so a cross-project call cannot
-use the source repository's policy or credentials. Relative paths,
-mixed-project calls, unknown schemas, and absolute paths outside a recognized
-repository/marker keep the payload cwd. Free-form shell commands are not
-reinterpreted as project routing instructions. This changes raw observation
+Some harnesses report a cwd other than where a tool ran: a subagent keeps its
+parent session's cwd while using a file tool in another checkout, and Hermes
+Agent always reports its own process directory (usually `~`) while each tool
+call names its repository through `workdir` or `path`. Native `ai-memory hook`
+commands compensate before applying `follow-cwd` or `sticky`: a tool call's
+absolute location — a fixture-backed file tool's target paths, a search/list
+tool's explicit `path`, or a shell command's structured `workdir` — routes the
+event when every path proves the same repository or marker boundary. That
+destination's marker decides allowlist admission, and its capture policy and
+`server` profile apply, so a cross-project call cannot use the source
+repository's credentials. The source's exclusions still bind: if the payload
+cwd's own `ignore_paths` would drop the event (a pattern can name a path
+outside its checkout, and a command can name a source file while its `workdir`
+points elsewhere), the event is not rerouted and that exclusion drops it.
+Relative paths and workdirs, mixed-project calls, unknown schemas, and absolute
+paths outside a recognized repository/marker keep the payload cwd. Free-form
+shell command text is never reinterpreted as a project routing instruction;
+only the structured `workdir` field counts. This changes raw observation
attribution only; the session row and its compiled session page remain in the
project where the session began.
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 5f0bd95d..1701cebf 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -70,7 +70,7 @@ boundary not yet built.
| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |
| 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |
-| 11g | Cross-project file attribution cannot bypass destination capture or server routing (#932) | `ai-memory-hooks/src/capture_policy.rs` `absolute_file_tool_paths` accepts only bounded, recognized, absolute file-tool candidates; `ai-memory-cli/src/commands/hook.rs` `file_tool_routing_cwd` requires every path to prove the same repository/marker boundary and resolves that destination before capture policy, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths` | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |
+| 11g | Cross-project tool attribution cannot bypass source or destination capture, or destination server routing (#932, #1199) | `ai-memory-hooks/src/capture_policy.rs` `absolute_tool_location_paths` accepts only bounded, recognized, absolute locations: file-tool targets, a search/list tool's explicit `path`, or a shell command's structured `workdir` (command text is never parsed for a location); `ai-memory-cli/src/commands/hook.rs` `tool_location_routing_cwd` requires every path to prove the same repository/marker boundary, refuses the reroute when the payload cwd's own capture policy would not keep the event (source `ignore_paths` may name paths outside the source checkout, and a command may name source files while its `workdir` points elsewhere), and resolves that destination before capture policy, allowlist marker, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths`, `workdir_reroute_applies_the_destination_capture_policy` (a `workdir`-rerouted command reading a destination-excluded path is dropped, public control kept), **`a_reroute_cannot_escape_the_source_capture_exclusions`** (adversarial: a file read under a source pattern that names another project's directory, and a shell command naming an excluded source file with `workdir` in another project, are both refused; public file and shell controls still reroute — fails with the source-policy check removed), `hermes_tool_location_finds_the_marker_the_process_cwd_lacks` (Hermes `terminal` `workdir`, `read_file` `path` and `search_files` `path` reach the repository marker under allowlist; no-workdir, relative-workdir and relative-search controls stay with the unmarked process cwd); `capture_policy.rs` `absolute_tool_location_paths_cover_search_dirs_and_shell_workdirs` (relative workdir, command-text paths, workdir without a command, and Hermes `process` yield no location) | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |
| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |
| 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index e0624903..93837f12 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -39,7 +39,7 @@
| VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |
| Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. |
| Muse Code | MCP-only | `install-mcp --client muse` merges a native streamable-HTTP entry with bearer `headers` into the snake_case `mcp_servers` map of `~/.config/muse/settings.json`, preserving sibling servers. The writer adds the mandatory `"schema_version": 1` when absent (without it every `muse` command fails at startup) and never rewrites an existing value, and it sets `"mode": "optional"` because Muse's default `required` aborts the whole run when the server is unreachable. Skills need no extra step: Muse reads `~/.agents/skills`, which `install-skills` already writes. Lifecycle capture and managed workstreams are not claimed — Muse documents a hook surface, but the output contract of its `SessionStart` event is not specified. |
-| Hermes Agent | Supported | `install-hooks --agent hermes` (alias `hermes-agent`) prints a ready-to-paste `hooks:` block for `~/.hermes/config.yaml`. Hermes splits each configured `command` with `shlex.split` and runs it with no shell, passing the event JSON on stdin, so the entries invoke the native `ai-memory hook` command (exec form, like Zero and ZCode — no script bundle is staged); ai-memory never writes that YAML file, which is yours to edit and which Hermes itself gates behind its hook-acceptance prompt (`hooks_auto_accept`). Two tool events are wired, `pre_tool_call` → `pre-tool-use` and `post_tool_call` → `post-tool-use`; their `tool_name` / `tool_input` payload drives concrete session attribution, tool-family titles, and capture exclusions. Session lifecycle (recall, prompt capture, session-end, automatic handoff) is owned by the community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) memory provider, so no hook-driven `session-end` is installed and nothing is duplicated; review that plugin's compatibility matrix, install/uninstall scripts, and secret handling before enabling it. No first-party `install-mcp` client and no managed workstream are claimed yet, and because Hermes ignores session-start hook stdout a pending handoff is recovered through MCP (`memory_handoff_list` then `memory_handoff_accept`). |
+| Hermes Agent | Supported | `install-hooks --agent hermes` (alias `hermes-agent`) prints a ready-to-paste `hooks:` block for `~/.hermes/config.yaml`. Hermes splits each configured `command` with `shlex.split` and runs it with no shell, passing the event JSON on stdin, so the entries invoke the native `ai-memory hook` command (exec form, like Zero and ZCode — no script bundle is staged); ai-memory never writes that YAML file, which is yours to edit and which Hermes itself gates behind its hook-acceptance prompt (`hooks_auto_accept`). Two tool events are wired, `pre_tool_call` → `pre-tool-use` and `post_tool_call` → `post-tool-use`; their `tool_name` / `tool_input` payload drives concrete session attribution, tool-family titles, and capture exclusions. Hermes reports its own process directory as `cwd`, so the native hook locates each event's `.ai-memory.toml` from the tool's absolute `workdir` (`terminal`) or `path` (file tools, `search_files`); a call with no absolute location stays with the process directory. Session lifecycle (recall, prompt capture, session-end, automatic handoff) is owned by the community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) memory provider, so no hook-driven `session-end` is installed and nothing is duplicated; review that plugin's compatibility matrix, install/uninstall scripts, and secret handling before enabling it. No first-party `install-mcp` client and no managed workstream are claimed yet, and because Hermes ignores session-start hook stdout a pending handoff is recovered through MCP (`memory_handoff_list` then `memory_handoff_accept`). |
| GrizzyBot | Supported | [GrizzyBot](https://github.com/Foscoe63/GrizzyBot), a native macOS agent app, ships its own ai-memory bridge: it posts lifecycle events to `/hook` with `agent=grizzybot` (alias `grizzy-bot`) and talks to `/mcp` directly, so there is nothing for `install-hooks` or `install-mcp` to write. Sessions are attributed to `grizzybot`, and its Claude Code-shaped tool payloads (`tool_name`/`tool_input`/`tool_use_id`) are stored as closed-schema tool families, never tool names or arguments. The bridge is maintained in the GrizzyBot repository; review it before pointing it at a shared server. No managed workstream. |
| LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode (Go and Zen), OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. |
| Embedding providers | Supported | OpenAI, Voyage, Google Gemini, and keyless OpenAI-compatible endpoints such as Ollama, LM Studio, and vLLM. |