Skip to content

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

Rust

fix(hooks): capture Claude Code tool failures via PostToolUseFailure

gb246b659d17c7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12202b0f..fbed3e4f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,18 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- Captured Claude Code tool failures. Claude Code fires `PostToolUseFailure`,
+ not `PostToolUse`, when a tool fails, and ai-memory never wired that event
+ for Claude Code, so failed commands, builds and test runs never reached
+ capture, search, consolidation or the handoff. `install-hooks --agent
+ claude-code`, `setup` and the marketplace plugin now wire it to the
+ post-tool-use handler; the observation records `outcome: error` with the
+ bounded error text (never the tool's arguments); the session page counts
+ failed calls and quotes the newest one; the automatic handoff adds a `Last
+ failed tool call` line; and the plugin no longer drops a failure when
+ settings hooks wire only the success event. Re-run `ai-memory install-hooks
+ --agent claude-code --apply` (or `ai-memory setup`) on an existing install.
+ Grok Build CLI keeps its nine events (#1893).
- Project search links now use the project's current stored name after
resolving a canonical or legacy key. Results, breadcrumbs, and the scope
selector stay on that project without renaming it (#1875).
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 135026ae..d9abaf8d 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -1034,7 +1034,16 @@ fn is_dropped_plugin_copy(
};
let (cwd, _) = hook_context(&args.agent, raw);
let settings = settings_files_for(origin, cwd.as_deref(), &mut lookup);
- drops_plugin_event(origin, &args.event, cwd.as_deref(), &settings)
+ let harness_event = raw
+ .get("hook_event_name")
+ .and_then(serde_json::Value::as_str);
+ drops_plugin_event(
+ origin,
+ &args.event,
+ harness_event,
+ cwd.as_deref(),
+ &settings,
+ )
}
fn write_success_response<W: std::io::Write>(
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 7db8f1ad..efbcb593 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -6772,7 +6772,7 @@ fn render_grok(
) -> Result<()> {
// Soft check (same rationale as render_claude_code): warn, don't bail,
// so the docker host-path flow still works.
- for (_, script) in super::render_shared::CLAUDE_CODE_EVENTS {
+ for (_, script) in super::render_shared::GROK_EVENTS {
let script = hook_script_for_claude_code(script);
let abs = hooks_dir.join(script.as_ref());
if !abs.exists() {
@@ -16208,6 +16208,17 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
"generated command must reference staged script {}: {command}",
staged_script.display()
);
+ // The failure event shares the post-tool-use handler.
+ let failure = parsed
+ .pointer("/hooks/PostToolUseFailure/0/hooks/0/command")
+ .and_then(serde_json::Value::as_str)
+ .expect("PostToolUseFailure command should be present");
+ assert_eq!(
+ Some(failure),
+ parsed
+ .pointer("/hooks/PostToolUse/0/hooks/0/command")
+ .and_then(serde_json::Value::as_str)
+ );
}
#[test]
diff --git a/crates/ai-memory-cli/src/commands/plugin_origin.rs b/crates/ai-memory-cli/src/commands/plugin_origin.rs
index 3bae08a5..975d1c10 100644
--- a/crates/ai-memory-cli/src/commands/plugin_origin.rs
+++ b/crates/ai-memory-cli/src/commands/plugin_origin.rs
@@ -60,19 +60,22 @@ impl PluginOrigin {
/// sits.
pub(crate) type SettingsHooks = (PathBuf, HooksFileShape);
-/// Whether a plugin-launched event must be dropped before capture. `cwd` is
-/// the payload's working directory; `settings_files` are the files whose
-/// ai-memory hooks outrank the plugin (see [`settings_files_for`]).
+/// Whether a plugin-launched event must be dropped before capture. `event` is
+/// the wire event the launcher passed and `harness_event` the payload's own
+/// `hook_event_name` (see [`settings_event_name`]); `cwd` is the payload's
+/// working directory; `settings_files` are the files whose ai-memory hooks
+/// outrank the plugin (see [`settings_files_for`]).
pub(crate) fn drops_plugin_event(
origin: PluginOrigin,
event: &str,
+ harness_event: Option<&str>,
cwd: Option<&str>,
settings_files: &[SettingsHooks],
) -> bool {
if is_folderless(cwd) {
return true;
}
- let Some(name) = settings_event_name(origin, event) else {
+ let Some(name) = settings_event_name(origin, event, harness_event) else {
// Muse's subagent events come from its built-in reminder observers,
// each under its own session id, every turn; `install-hooks --agent
// muse` leaves them out, and so does the plugin.
@@ -167,22 +170,34 @@ pub(crate) fn settings_files_for(
/// The settings-file event name for a wire event (`session-start` →
/// `SessionStart`).
-fn settings_event_name(origin: PluginOrigin, event: &str) -> Option<&'static str> {
- match origin {
- PluginOrigin::ClaudeCode => CLAUDE_CODE_EVENTS
- .iter()
- .find(|(_, script)| script.strip_suffix(".sh") == Some(event))
- .map(|(name, _)| *name),
- PluginOrigin::Droid => DROID_EVENTS
- .iter()
- .find(|(_, script)| script.strip_suffix(".sh") == Some(event))
- .map(|(name, _)| *name),
- PluginOrigin::Muse => MUSE_EVENTS
+///
+/// Two settings events can share one wire event (`PostToolUse` and
+/// `PostToolUseFailure` both run `post-tool-use`). The harness's own event
+/// name picks between them; otherwise the first entry wins. So settings that
+/// wire only the success event do not silence the plugin's failure copy.
+fn settings_event_name(
+ origin: PluginOrigin,
+ event: &str,
+ harness_event: Option<&str>,
+) -> Option<&'static str> {
+ let events: &[(&'static str, &'static str)] = match origin {
+ PluginOrigin::ClaudeCode => &CLAUDE_CODE_EVENTS,
+ PluginOrigin::Droid => &DROID_EVENTS,
+ PluginOrigin::Muse => &MUSE_EVENTS,
+ PluginOrigin::Codex => return None,
+ };
+ let names = || {
+ events
.iter()
- .find(|(_, script)| script.strip_suffix(".sh") == Some(event))
- .map(|(name, _)| *name),
- PluginOrigin::Codex => None,
- }
+ .filter(|(_, script)| script.strip_suffix(".sh") == Some(event))
+ .map(|(name, _)| *name)
+ };
+ let first = names().next()?;
+ Some(
+ names()
+ .find(|name| Some(*name) == harness_event)
+ .unwrap_or(first),
+ )
}
/// A session with no project folder: no `cwd` at all, or one inside a Claude
@@ -268,16 +283,18 @@ mod tests {
assert!(drops_plugin_event(
PluginOrigin::ClaudeCode,
"session-start",
+ None,
cwd,
&files
));
assert!(
- !drops_plugin_event(PluginOrigin::ClaudeCode, "stop", cwd, &files),
+ !drops_plugin_event(PluginOrigin::ClaudeCode, "stop", None, cwd, &files),
"an event the settings hooks do not wire stays with the plugin"
);
assert!(!drops_plugin_event(
PluginOrigin::ClaudeCode,
"session-start",
+ None,
cwd,
&[(temp.path().join("missing.json"), HooksFileShape::HooksKey)]
));
@@ -290,6 +307,7 @@ mod tests {
assert!(!drops_plugin_event(
PluginOrigin::ClaudeCode,
"session-start",
+ None,
cwd,
&files
));
@@ -298,6 +316,77 @@ mod tests {
assert!(!drops_plugin_event(
PluginOrigin::ClaudeCode,
"session-start",
+ None,
+ cwd,
+ &files
+ ));
+ }
+
+ /// Adversarial: settings that wire only `PostToolUse` must not drop the
+ /// plugin's `PostToolUseFailure` copy. Controls: the success copy, a
+ /// payload without a harness event, and settings wiring both are dropped.
+ #[test]
+ fn a_plugin_failure_copy_is_dropped_only_when_settings_deliver_the_failure_event() {
+ let temp = tempfile::tempdir().unwrap();
+ let settings = temp.path().join("settings.json");
+ let cwd = Some("/work/repo");
+ let files = vec![(settings.clone(), HooksFileShape::HooksKey)];
+ let entry = |event: &str| {
+ format!(
+ r#""{event}":[{{"matcher":"","hooks":[{{"type":"command","command":"/usr/bin/ai-memory hook --event post-tool-use --agent claude-code --server-url http://127.0.0.1:49374"}}]}}]"#
+ )
+ };
+ std::fs::write(
+ &settings,
+ format!(r#"{{"hooks":{{{}}}}}"#, entry("PostToolUse")),
+ )
+ .unwrap();
+ assert!(
+ !drops_plugin_event(
+ PluginOrigin::ClaudeCode,
+ "post-tool-use",
+ Some("PostToolUseFailure"),
+ cwd,
+ &files
+ ),
+ "settings deliver only the success event: the plugin keeps the failure"
+ );
+ assert!(drops_plugin_event(
+ PluginOrigin::ClaudeCode,
+ "post-tool-use",
+ Some("PostToolUse"),
+ cwd,
+ &files
+ ));
+ assert!(drops_plugin_event(
+ PluginOrigin::ClaudeCode,
+ "post-tool-use",
+ None,
+ cwd,
+ &files
+ ));
+ // An unrelated harness event falls back to the first mapping.
+ assert!(drops_plugin_event(
+ PluginOrigin::ClaudeCode,
+ "post-tool-use",
+ Some("SessionStart"),
+ cwd,
+ &files
+ ));
+
+ std::fs::write(
+ &settings,
+ format!(
+ r#"{{"hooks":{{{},{}}}}}"#,
+ entry("PostToolUse"),
+ entry("PostToolUseFailure")
+ ),
+ )
+ .unwrap();
+ assert!(drops_plugin_event(
+ PluginOrigin::ClaudeCode,
+ "post-tool-use",
+ Some("PostToolUseFailure"),
cwd,
&files
));
@@ -322,6 +411,7 @@ mod tests {
drops_plugin_event(
PluginOrigin::ClaudeCode,
"post-tool-use",
+ None,
Some("/work/repo"),
&files,
)
@@ -350,6 +440,7 @@ mod tests {
assert!(!drops_plugin_event(
PluginOrigin::Codex,
"session-start",
+ None,
Some("/work/repo"),
&[(settings, HooksFileShape::HooksKey)]
));
@@ -371,6 +462,7 @@ mod tests {
drops_plugin_event(
PluginOrigin::Droid,
event,
+ None,
Some("/work/repo"),
&droid_files(home),
)
@@ -428,11 +520,13 @@ mod tests {
PluginOrigin::Droid,
"user-prompt-submit",
None,
+ None,
&[]
));
assert!(!drops_plugin_event(
PluginOrigin::Droid,
"user-prompt-submit",
+ None,
Some("/work/repo"),
&[]
));
@@ -448,7 +542,7 @@ mod tests {
pairs.push(("XDG_CONFIG_HOME", xdg.as_str()));
}
let files = settings_files_for(PluginOrigin::Muse, Some("/work/repo"), lookup(&pairs));
- drops_plugin_event(PluginOrigin::Muse, event, Some("/work/repo"), &files)
+ drops_plugin_event(PluginOrigin::Muse, event, None, Some("/work/repo"), &files)
}
/// Adversarial: Muse running the Claude Code plugin next to an
@@ -485,6 +579,7 @@ mod tests {
!drops_plugin_event(
PluginOrigin::ClaudeCode,
"subagent-start",
+ None,
Some("/work/repo"),
&[]
),
@@ -510,11 +605,13 @@ mod tests {
PluginOrigin::Muse,
"user-prompt-submit",
None,
+ None,
&[]
));
assert!(!drops_plugin_event(
PluginOrigin::Muse,
"user-prompt-submit",
+ None,
Some("/work/repo"),
&[]
));
@@ -567,7 +664,13 @@ mod tests {
Some(r"C:\Users\me\AppData\Roaming\Claude\scratch-workspaces\a\b\scratch-1"),
] {
assert!(
- drops_plugin_event(PluginOrigin::ClaudeCode, "user-prompt-submit", cwd, &[]),
+ drops_plugin_event(
+ PluginOrigin::ClaudeCode,
+ "user-prompt-submit",
+ None,
+ cwd,
+ &[]
+ ),
"{cwd:?}"
);
}
@@ -580,6 +683,7 @@ mod tests {
!drops_plugin_event(
PluginOrigin::ClaudeCode,
"user-prompt-submit",
+ None,
Some(cwd),
&[]
),
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 77444485..8fb7981c 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -5,8 +5,8 @@
//! pieces of state:
//!
//! 1. The per-agent lifecycle-hook event lists ai-memory wires up
-//! (Claude/Grok share `CLAUDE_CODE_EVENTS`; Codex, Cursor, Gemini,
-//! and Antigravity define their own profiles) — kept in sync between
+//! (`CLAUDE_CODE_EVENTS`; Grok's own `GROK_EVENTS`; Codex, Cursor,
+//! Gemini, and Antigravity define their own profiles) — kept in sync between
//! hook-bundle generation (setup-agent) and config rendering
//! (install-hooks).
//! 2. The optional `Authorization: Bearer <token>` header used by
@@ -30,15 +30,23 @@ use crate::commands::path_util::strip_windows_verbatim_prefix;
/// Claude Code lifecycle events ai-memory hooks. Each pair is
/// `(event-name-in-Claude-Code-settings, POSIX hook-script-filename)`.
///
+/// `PostToolUse` fires only when a tool succeeds; `PostToolUseFailure` fires
+/// when it fails (<https://code.claude.com/docs/en/hooks>). Without the second
+/// entry every failed command, build and test run was invisible. It reuses the
+/// post-tool-use script: the server aliases the event and reads the outcome
+/// from the payload.
+///
/// Adding a hook event means updating this list AND adding the matching `.sh`
-/// and `.ps1` files under the agents that use this profile (`claude-code` and
-/// `grok`). Agents with different vocabularies keep their own event arrays
-/// below. The install-hooks parity test fails if a bundle drifts.
-pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [
+/// and `.ps1` files under `hooks/claude-code/` (a reused script like
+/// post-tool-use needs no new file). Agents with different vocabularies keep
+/// their own event arrays below. The install-hooks parity test fails if a
+/// bundle drifts.
+pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 10] = [
("SessionStart", "session-start.sh"),
("UserPromptSubmit", "user-prompt-submit.sh"),
("PreToolUse", "pre-tool-use.sh"),
("PostToolUse", "post-tool-use.sh"),
+ ("PostToolUseFailure", "post-tool-use.sh"),
("PreCompact", "pre-compact.sh"),
("Stop", "stop.sh"),
("SessionEnd", "session-end.sh"),
@@ -49,14 +57,29 @@ pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [
("SubagentStop", "subagent-stop.sh"),
];
+/// Grok Build CLI: Claude Code's JSON shape and the nine events Grok is known
+/// to fire. `PostToolUseFailure` waits until Grok's vocabulary is verified.
+/// Its script bundle is `hooks/grok/`.
+pub(crate) const GROK_EVENTS: [(&str, &str); 9] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+ ("SessionEnd", "session-end.sh"),
+ ("SubagentStart", "subagent-start.sh"),
+ ("SubagentStop", "subagent-stop.sh"),
+];
+
/// Claude Code otherwise gives SessionEnd hooks a 1.5-second shared budget.
/// A settings-file timeout raises that budget (up to Claude's 60-second cap),
/// leaving room for a slow local spool fsync without making other hooks wait.
pub(crate) const CLAUDE_SESSION_END_TIMEOUT_SECS: u64 = 15;
-/// Kimi Code lifecycle events ai-memory hooks. Claude Code's 9-event
-/// vocabulary (`CLAUDE_CODE_EVENTS`) plus `PostToolUseFailure`: Kimi Code
-/// fires `PostToolUse` on successful calls only and reports failures
+/// Kimi Code lifecycle events ai-memory hooks: the same ten events as
+/// Claude Code (`CLAUDE_CODE_EVENTS`), `PostToolUseFailure` included. Kimi
+/// Code fires `PostToolUse` on successful calls only and reports failures
/// separately. The failure entry reuses the post-tool-use script — the
/// server aliases `PostToolUseFailure` to `PostToolUse` and reads the
/// outcome from the payload.
@@ -89,7 +112,7 @@ pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 10] = [
/// its native camelCase one — this lets it free-ride on the same key-based
/// payload extraction as Claude Code/Codex/Zcode (see `tool_observation_metadata`
/// in `capture_policy.rs`) rather than needing a dedicated parser (#1040).
-/// Same vocabulary as `KIMI_CODE_EVENTS`: Claude Code's 9 events plus
+/// Same vocabulary as `KIMI_CODE_EVENTS` and `CLAUDE_CODE_EVENTS`, including
/// `PostToolUseFailure`, which Copilot (per
/// <https://docs.github.com/en/copilot/reference/hooks-configuration>) fires
/// instead of `PostToolUse` when a tool call errors — the server already
@@ -833,7 +856,7 @@ fn with_claude_session_end_timeout(mut payload: Value) -> Value {
}
/// Grok Build CLI hook payload for docker/setup-agent script snippets.
-/// Grok shares Claude Code's JSON shape and event vocabulary, but uses
+/// Grok shares Claude Code's JSON shape (`GROK_EVENTS`), but uses
/// its own script bundle so script fallback keeps `agent=grok` and never
/// destructively fetches handoffs on SessionStart.
#[must_use]
@@ -843,7 +866,7 @@ pub(crate) fn build_grok_payload(
auth_token: Option<&str>,
) -> serde_json::Value {
build_hook_payload_for_platform(
- &CLAUDE_CODE_EVENTS,
+ &GROK_EVENTS,
emit_root,
server_url,
auth_token,
@@ -1214,7 +1237,7 @@ pub(crate) fn build_grok_payload_with_data_dir(
project_strategy: Option<&str>,
) -> serde_json::Value {
build_hook_payload_for_platform(
- &CLAUDE_CODE_EVENTS,
+ &GROK_EVENTS,
emit_root,
server_url,
auth_token,
@@ -3969,13 +3992,32 @@ if (inheritOnly) {
v.pointer("/hooks/PostToolUse/0/hooks/0/timeout").is_none(),
"only the cancellation-prone SessionEnd budget is raised"
);
+ // The failure event shares the post-tool-use handler.
+ assert_eq!(
+ v.pointer("/hooks/PostToolUseFailure/0/hooks/0/command"),
+ v.pointer("/hooks/PostToolUse/0/hooks/0/command"),
+ "the failure event must reuse the post-tool-use handler"
+ );
+ }
+
+ /// Grok's vocabulary is unverified, so its payload keeps nine events.
+ #[test]
+ fn grok_payload_keeps_its_nine_events() {
+ let root = PathBuf::from("/host/hooks/grok");
+ let v = build_grok_payload(&root, "http://localhost:49374", None);
+ let hooks = v.get("hooks").and_then(|h| h.as_object()).unwrap();
+ assert_eq!(hooks.len(), GROK_EVENTS.len());
+ assert!(!hooks.contains_key("PostToolUseFailure"));
+ for (event, _) in GROK_EVENTS {
+ assert!(hooks.contains_key(event), "missing event {event}");
+ }
}
#[test]
fn grok_native_payload_uses_grok_agent() {
let root = PathBuf::from("/host/hooks/grok");
let v = build_hook_payload_for_platform(
- &CLAUDE_CODE_EVENTS,
+ &GROK_EVENTS,
&root,
"http://localhost:49374",
None,
@@ -3994,7 +4036,7 @@ if (inheritOnly) {
fn grok_script_payload_uses_grok_bundle() {
let root = PathBuf::from("/host/hooks/grok");
let v = build_hook_payload_for_platform(
- &CLAUDE_CODE_EVENTS,
+ &GROK_EVENTS,
&root,
"http://localhost:49374",
None,
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index e5343ff5..8de74f15 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -1187,9 +1187,10 @@ mod tests {
#[test]
fn kimi_code_manual_script_paths_cover_kimi_event_set() {
- // Kimi Code's hook vocabulary is Claude Code's nine events plus
- // PostToolUseFailure; the failure entry reuses post-tool-use.sh,
- // so the script list carries nine unique files for ten events.
+ // Kimi Code's hook vocabulary is Claude Code's ten events,
+ // PostToolUseFailure included; the failure entry reuses
+ // post-tool-use.sh, so the script list carries nine unique files for
+ // ten events.
let root = Path::new("/hooks/kimi-code");
let paths = event_script_paths(root, &[&KIMI_CODE_EVENTS]);
let rendered = paths
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 926b72eb..1d24e699 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -83,8 +83,9 @@ pub use message::{
NewAgentMessage, UNTRUSTED_MESSAGE_NOTICE,
};
pub use observation::{
- NewObservation, NewSession, NewSessionUsage, Observation, ObservationKind, TokenCall,
- TokenCallContext, TokenToolRef, TokenToolRelation,
+ FAILED_TOOL_OUTCOME_LINE, NewObservation, NewSession, NewSessionUsage, Observation,
+ ObservationKind, TOOL_BODY_HEADER_MAX_CHARS, TOOL_BODY_SEPARATOR, TOOL_OUTCOME_LINE_PREFIX,
+ TokenCall, TokenCallContext, TokenToolRef, TokenToolRelation,
};
pub use page::{
FeedbackKind, LinkTarget, MAX_ENTITIES_PER_PAGE, MAX_ENTITY_LEN, NewPage, Page, PageEvidence,
diff --git a/crates/ai-memory-core/src/observation.rs b/crates/ai-memory-core/src/observation.rs
index e0b78eb3..72d0f520 100644
--- a/crates/ai-memory-core/src/observation.rs
+++ b/crates/ai-memory-core/src/observation.rs
@@ -12,6 +12,20 @@ use serde::{Deserialize, Serialize};
use crate::ids::{AgentKind, ObservationId, ProjectId, SessionId, WorkspaceId};
+/// Splits a tool observation body into its metadata header (`tool_family:
+/// …`, ids, `outcome: …`) and its output excerpt.
+pub const TOOL_BODY_SEPARATOR: &str = "\n---\n";
+
+/// Starts the header's outcome line; the outcome follows.
+pub const TOOL_OUTCOME_LINE_PREFIX: &str = "\noutcome: ";
+
+/// The header's last line when the harness reported the call as failed.
+pub const FAILED_TOOL_OUTCOME_LINE: &str = "\noutcome: error";
+
+/// Readers check the header on this many leading characters only. Every
+/// header the router writes fits, so an output excerpt is never scanned.
+pub const TOOL_BODY_HEADER_MAX_CHARS: usize = 512;
+
/// Classification of a single observation, mirroring the headline
/// Claude Code / Codex lifecycle hook events.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 61027356..d36f1cee 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -483,7 +483,15 @@ pub(crate) fn tool_observation_outcome(agent: AgentKind, raw: &Value) -> ToolOut
// Meta Muse Code's `PostToolUseFailure` has the same `error` string
// (captured offline on Muse Code 1.4.7); its `PostToolUse` proves no
// outcome.
- AgentKind::Zcode | AgentKind::Muse | AgentKind::QwenCode | AgentKind::Qoder
+ // Claude Code's `PostToolUseFailure` carries the same `error` string
+ // (<https://code.claude.com/docs/en/hooks>); an aborted call
+ // (`is_interrupt`) did not succeed either. Its `PostToolUse` fires
+ // only on success and has no `error` key.
+ AgentKind::Zcode
+ | AgentKind::Muse
+ | AgentKind::QwenCode
+ | AgentKind::Qoder
+ | AgentKind::ClaudeCode
if raw
.get("error")
.and_then(Value::as_str)
@@ -5737,6 +5745,56 @@ mod tests {
assert!(tool_observation_metadata(AgentKind::Grizzybot, &no_input, false).is_some());
}
+ /// Claude Code's documented `PostToolUseFailure` payload proves an error;
+ /// its success payload proves nothing.
+ #[test]
+ fn claude_code_post_tool_use_failure_error_maps_to_error_outcome() {
+ let failure = json!({
+ "hook_event_name": "PostToolUseFailure",
+ "tool_name": "Bash",
+ "tool_input": {"command": "npm test", "description": "Run test suite"},
+ "tool_use_id": "toolu_01ABC123",
+ "error": "Exit code 1
+ Error: Cannot find module 'express'",
+ "is_interrupt": false,
+ "duration_ms": 4187
+ });
+ assert_eq!(
+ tool_observation_outcome(AgentKind::ClaudeCode, &failure),
+ ToolOutcome::Error
+ );
+ // An abort is still a call that did not succeed.
+ let interrupted = json!({
+ "hook_event_name": "PostToolUseFailure",
+ "tool_name": "Bash",
+ "tool_input": {"command": "sleep 100"},
+ "error": "Command aborted",
+ "is_interrupt": true
+ });
+ assert_eq!(
+ tool_observation_outcome(AgentKind::ClaudeCode, &interrupted),
+ ToolOutcome::Error
+ );
+ // Control: a success and an empty `error` stay unknown.
+ let success = json!({
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Bash",
+ "tool_input": {"command": "npm test"},
+ "tool_response": {"stdout": "ok", "stderr": "", "interrupted": false}
+ });
+ assert_eq!(
+ tool_observation_outcome(AgentKind::ClaudeCode, &success),
+ ToolOutcome::Unknown
+ );
+ assert_eq!(
+ tool_observation_outcome(
+ AgentKind::ClaudeCode,
+ &json!({"tool_name": "Bash", "error": ""})
+ ),
+ ToolOutcome::Unknown
+ );
+ }
+
#[test]
fn zcode_post_tool_use_failure_error_maps_to_error_outcome() {
// Live-captured PostToolUseFailure payload (run 10, real model, #512):
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 0da80d6b..8aed3d1c 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -1,7 +1,8 @@
//! Wire envelope received on `POST /hook`.
use ai_memory_core::{
- AgentKind, OBSERVATION_BODY_MAX_BYTES, ObservationKind, Sanitizer, truncate_utf8_bytes,
+ AgentKind, OBSERVATION_BODY_MAX_BYTES, ObservationKind, Sanitizer, TOOL_BODY_SEPARATOR,
+ TOOL_OUTCOME_LINE_PREFIX, truncate_utf8_bytes,
};
use serde::{Deserialize, Serialize};
@@ -1045,7 +1046,7 @@ fn safe_tool_body(
match event {
HookEvent::PreToolUse => Some(summary),
HookEvent::PostToolUse => {
- summary.push_str("\noutcome: ");
+ summary.push_str(TOOL_OUTCOME_LINE_PREFIX);
summary.push_str(tool_observation_outcome(agent, raw).as_str());
if metadata.tool_family == crate::capture_policy::ToolFamily::Unknown {
return Some(summary);
@@ -1083,7 +1084,7 @@ fn safe_tool_body(
.or_else(|| antigravity_edit_content(agent, raw))
}
.unwrap_or_else(|| "(no output captured)".into());
- summary.push_str("\n---\n");
+ summary.push_str(TOOL_BODY_SEPARATOR);
summary.push_str(&result);
Some(summary)
}
@@ -3661,6 +3662,74 @@ mod tests {
assert!(!body.contains("SENTINEL_COMMAND"), "{body:?}");
}
+ /// A Claude Code `PostToolUseFailure` lands on the post-tool-use channel
+ /// with `outcome: error` and the error text, never the tool's arguments.
+ #[test]
+ fn claude_code_post_tool_use_failure_records_the_error_outcome_and_text() {
+ let failure = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "PostToolUseFailure".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": "s",
+ "hook_event_name": "PostToolUseFailure",
+ "tool_name": "Bash",
+ "tool_input": {"command": "npm test SENTINEL_COMMAND", "description": "Run test suite"},
+ "tool_use_id": "toolu_01ABC123",
+ "error": "Exit code 1
+ Error: Cannot find module 'express'",
+ "is_interrupt": false,
+ "duration_ms": 4187
+ }),
+ );
+ assert_eq!(failure.event, HookEvent::PostToolUse);
+ assert_eq!(failure.title_hint.as_deref(), Some("tool non-file"));
+ let body = failure.body_excerpt.expect("failure body");
+ assert!(body.contains("tool_family: non-file"), "{body:?}");
+ assert!(
+ body.contains(
+ "
+outcome: error
+---
+"
+ ),
+ "{body:?}"
+ );
+ assert!(body.contains("Exit code 1"), "{body:?}");
+ assert!(body.contains("Cannot find module 'express'"), "{body:?}");
+ assert!(!body.contains("SENTINEL_COMMAND"), "{body:?}");
+
+ // Control: a success body is unchanged.
+ let success = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": "s",
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Bash",
+ "tool_input": {"command": "npm test"},
+ "tool_response": {"stdout": "42 passing", "stderr": "", "interrupted": false},
+ "tool_use_id": "toolu_01ABC124",
+ }),
+ );
+ let body = success.body_excerpt.expect("success body");
+ assert!(
+ body.contains(
+ "
+outcome: unknown
+---
+"
+ ),
+ "{body:?}"
+ );
+ assert!(body.contains("42 passing"), "{body:?}");
+ }
+
/// Grok Build CLI posts a `PostToolUse` with Claude Code's snake_case
/// aliases (`tool_name` / `tool_input` / `tool_use_id`). It was absent from
/// both `closed_tool_agent` and the `tool_observation_metadata` match, so
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 6c2e49f7..fa24299e 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -5702,10 +5702,14 @@ fn build_auto_handoff(
summary.push_str("\n\nLatest assistant response: ");
summary.push_str(assistant);
}
- let next_steps = if facts.tools.is_empty() {
- Vec::new()
- } else {
- vec![format!(
+ let mut next_steps = Vec::new();
+ // The newest failed call and its error: what broke is the first question.
+ // It may have been fixed later, so it is a report, not an open question.
+ if let Some(failed) = &facts.last_failed_tool {
+ next_steps.push(format!("Last failed tool call: {}", failed.describe()));
+ }
+ if !facts.tools.is_empty() {
+ next_steps.push(format!(
"Tools used: {}",
facts
.tools
@@ -5713,8 +5717,8 @@ fn build_auto_handoff(
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ")
- )]
- };
+ ));
+ }
NewHandoff {
workspace_id,
project_id,
@@ -24690,6 +24694,82 @@ pub(crate) mod tests {
);
}
+ /// The baton names the newest failed call with its error text; a family
+ /// label names no tool.
+ #[test]
+ fn auto_handoff_names_the_last_failed_tool_call() {
+ use ai_memory_core::{ProjectId, WorkspaceId};
+ let handoff_for = |rows: &[ai_memory_core::Observation]| {
+ build_auto_handoff(
+ WorkspaceId::new(),
+ ProjectId::new(),
+ AgentKind::ClaudeCode,
+ SessionId::new(),
+ None,
+ rows,
+ None,
+ false,
+ )
+ };
+ let observations = vec![
+ mk_obs(ObservationKind::UserPrompt, "fix bug", "fix the bug"),
+ mk_obs(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\ntool_call_id: toolu_1\noutcome: error\n---\n\
+ Exit code 1\nError: Cannot find module 'express'",
+ ),
+ mk_obs(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\ntool_call_id: toolu_2\noutcome: error\n---\n\
+ Exit code 2\nerror[E0425]: cannot find value `x`",
+ ),
+ mk_obs(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\noutcome: unknown\n---\n42 passing",
+ ),
+ mk_obs(ObservationKind::Stop, "stop", ""),
+ ];
+ let handoff = handoff_for(&observations);
+ assert_eq!(
+ handoff.next_steps,
+ vec![
+ "Last failed tool call: Bash: Exit code 2 error[E0425]: cannot find value `x`"
+ .to_string(),
+ "Tools used: Bash".to_string(),
+ ]
+ );
+
+ // A family label names no tool.
+ let bare = vec![
+ mk_obs(ObservationKind::UserPrompt, "fix bug", "fix the bug"),
+ mk_obs(
+ ObservationKind::PostToolUse,
+ "tool file",
+ "tool_family: file\noutcome: error\n---\nENOENT: no such file",
+ ),
+ ];
+ let handoff = handoff_for(&bare);
+ assert_eq!(
+ handoff.next_steps,
+ vec!["Last failed tool call: ENOENT: no such file".to_string()]
+ );
+
+ // Control: no failure, no line.
+ let fine = vec![
+ mk_obs(ObservationKind::UserPrompt, "fix bug", "fix the bug"),
+ mk_obs(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\noutcome: unknown\n---\n42 passing",
+ ),
+ ];
+ let handoff = handoff_for(&fine);
+ assert_eq!(handoff.next_steps, vec!["Tools used: Bash".to_string()]);
+ }
+
/// `[ingest] record_tool_names` titles (`tool <family>: <name>`) list by
/// their name in `Tools used:`, while the family they still carry keeps
/// the file-activity heuristic firing.
diff --git a/crates/ai-memory-hooks/src/session_end_equivalence.rs b/crates/ai-memory-hooks/src/session_end_equivalence.rs
index 1920f28c..454011a8 100644
--- a/crates/ai-memory-hooks/src/session_end_equivalence.rs
+++ b/crates/ai-memory-hooks/src/session_end_equivalence.rs
@@ -12,6 +12,11 @@
//! Each test seeds sessions into a real store, runs the oracle on the rows
//! `observations_for_session` returns, runs the production path on the same
//! session, and compares the outputs.
+//!
+//! The failed-call facts (`## Failed tool calls`, the `N failed` clause, the
+//! handoff's `Last failed tool call` line) post-date the oracle. No fixture
+//! here has a failed call; `failed_tool_facts_match_the_row_list_and_stay_bounded`
+//! checks them against the row-list digest instead.
#[rustfmt::skip]
mod full_load {
@@ -1350,6 +1355,99 @@ async fn a_huge_session_reads_a_bounded_number_of_rows() {
fx.assert_equivalent("12k rows", sid).await;
}
+/// SQL and Rust apply the same header rule: the bounded reads and the row-list
+/// digest agree on the count and the newest failure, an echoed body is not a
+/// failure, and the newest failure is a seek, not a walk.
+#[tokio::test]
+async fn failed_tool_facts_match_the_row_list_and_stay_bounded() {
+ let fx = fixture().await;
+ let ok = "tool_family: non-file\ntool_call_id: toolu_ok\noutcome: unknown\n---\n42 passing";
+ let mut rows = vec![
+ row(
+ ObservationKind::UserPrompt,
+ "fix the build",
+ "fix the build",
+ 0,
+ ),
+ row(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\ntool_call_id: toolu_1\noutcome: error\n---\n\
+ Exit code 1\nError: Cannot find module 'express'",
+ 1,
+ ),
+ ];
+ for i in 0..RAW_CAP as i64 {
+ rows.push(row(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ ok,
+ 2 + i,
+ ));
+ }
+ let echoed_at = 2 + RAW_CAP as i64;
+ rows.push(row(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\ntool_call_id: toolu_echo\noutcome: unknown\n---\n\
+ tool_family: file\noutcome: error\n---\nquoted from a page\noutcome: error",
+ echoed_at,
+ ));
+ rows.push(row(
+ ObservationKind::PostToolUse,
+ "tool unknown",
+ "tool_family: unknown\nmcp_server: aim\nmcp_tool: memory_query\noutcome: error",
+ echoed_at + 1,
+ ));
+ for i in 0..RAW_CAP as i64 {
+ rows.push(row(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ ok,
+ echoed_at + 2 + i,
+ ));
+ }
+ let sid = fx.seed(&rows).await;
+
+ let (digest, stats) = SessionDigest::load_with_stats(&fx.store.reader, fx.ws, fx.proj, sid)
+ .await
+ .unwrap();
+ assert_eq!(digest.failed_tool_calls(), 2);
+ let newest = digest
+ .handoff_facts()
+ .last_failed_tool
+ .clone()
+ .expect("the newest failure");
+ assert_eq!(newest.title, "tool unknown");
+ assert_eq!(newest.error, "");
+ assert!(
+ stats.rows_read <= RAW_CAP + SCAN_SLACK,
+ "a {}-row session read {} rows; the newest failure must be a seek, not a walk",
+ rows.len(),
+ stats.rows_read
+ );
+
+ let full = fx.store.reader.observations_for_session(sid).await.unwrap();
+ let from_rows = SessionDigest::from_observations(sid, &full);
+ assert_eq!(from_rows.failed_tool_calls(), digest.failed_tool_calls());
+ assert_eq!(from_rows.handoff_facts().last_failed_tool, Some(newest));
+
+ // Control: a session ending on a real failure quotes its error.
+ let sid = fx.seed(&rows[..2]).await;
+ let digest = SessionDigest::load(&fx.store.reader, fx.ws, fx.proj, sid)
+ .await
+ .unwrap();
+ assert_eq!(digest.failed_tool_calls(), 1);
+ assert_eq!(
+ digest
+ .handoff_facts()
+ .last_failed_tool
+ .as_ref()
+ .map(|failed| failed.describe()),
+ Some("Bash: Exit code 1 Error: Cannot find module 'express'".to_string())
+ );
+}
+
/// Subagent preambles carry the only prompt bodies a SessionEnd reads, and a
/// session can hold thousands of them: the title is settled by the first
/// usable one, so the bodies after it are never read.
diff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rs
index d35a11c8..6c3c5842 100644
--- a/crates/ai-memory-hooks/src/synth.rs
+++ b/crates/ai-memory-hooks/src/synth.rs
@@ -18,8 +18,9 @@
use std::collections::{BTreeMap, BTreeSet};
use ai_memory_core::{
- AgentKind, NewPage, Observation, ObservationKind, PagePath, ProjectId, SessionId, Tier,
- WorkspaceId, looks_like_markup_block, looks_like_scaffolding, truncate_for_title,
+ AgentKind, FAILED_TOOL_OUTCOME_LINE, NewPage, Observation, ObservationKind, PagePath,
+ ProjectId, SessionId, TOOL_BODY_HEADER_MAX_CHARS, TOOL_BODY_SEPARATOR, Tier, WorkspaceId,
+ looks_like_markup_block, looks_like_scaffolding, truncate_for_title, truncate_utf8_bytes,
};
use ai_memory_store::{
ObservationOrder, ReaderPool, SessionKindSummary, SessionLine, SessionObservationSnapshot,
@@ -120,6 +121,71 @@ struct SessionEndFact {
body: String,
}
+/// Bytes of error text the page and the handoff quote.
+const FAILED_TOOL_EXCERPT_BYTES: usize = 240;
+
+/// A tool call the harness reported as failed.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct FailedToolFact {
+ /// A recorded tool name or a family label.
+ pub(crate) title: String,
+ /// Error text after the header, whitespace-collapsed and capped at
+ /// [`FAILED_TOOL_EXCERPT_BYTES`]; empty when none was stored.
+ pub(crate) error: String,
+}
+
+impl FailedToolFact {
+ /// `"Bash: Exit code 1 …"`, or the error alone when the title is a family
+ /// label, which names no tool.
+ pub(crate) fn describe(&self) -> String {
+ let error = if self.error.is_empty() {
+ "(no error text captured)"
+ } else {
+ self.error.as_str()
+ };
+ match listable_tool_name(&self.title) {
+ Some(name) => format!("{name}: {error}"),
+ None => error.to_string(),
+ }
+ }
+}
+
+/// A `post-tool-use` whose header (the text before the first
+/// [`TOOL_BODY_SEPARATOR`], within the first [`TOOL_BODY_HEADER_MAX_CHARS`]
+/// characters) ends in [`FAILED_TOOL_OUTCOME_LINE`]. The store counts with
+/// the same rule, so an `outcome: error` line inside a tool's output never
+/// counts.
+fn is_failed_tool(obs: &Observation) -> bool {
+ if obs.kind != ObservationKind::PostToolUse {
+ return false;
+ }
+ let body = obs.body.as_str();
+ let head = body
+ .char_indices()
+ .nth(TOOL_BODY_HEADER_MAX_CHARS)
+ .map_or(body, |(end, _)| &body[..end]);
+ let header = head
+ .split_once(TOOL_BODY_SEPARATOR)
+ .map_or(head, |(header, _)| header);
+ header.ends_with(FAILED_TOOL_OUTCOME_LINE)
+}
+
+/// [`is_failed_tool`] with the quoted error text.
+fn failed_tool_fact(obs: &Observation) -> Option<FailedToolFact> {
+ if !is_failed_tool(obs) {
+ return None;
+ }
+ let output = obs
+ .body
+ .split_once(TOOL_BODY_SEPARATOR)
+ .map_or("", |(_, output)| output);
+ let collapsed = output.split_whitespace().collect::<Vec<_>>().join(" ");
+ Some(FailedToolFact {
+ title: obs.title.clone(),
+ error: truncate_utf8_bytes(&collapsed, FAILED_TOOL_EXCERPT_BYTES),
+ })
+}
+
/// Everything the auto-handoff and the abrupt-ending note read from a
/// session's observations, besides what [`SessionDigest`] already counts.
///
@@ -137,6 +203,8 @@ pub(crate) struct HandoffFacts {
pub(crate) question_prompt: Option<PromptFact>,
/// Title of the last completed tool call.
pub(crate) last_tool_title: Option<String>,
+ /// The newest failed call.
+ pub(crate) last_failed_tool: Option<FailedToolFact>,
/// Body of the last `Stop` that carries assistant text.
pub(crate) latest_assistant: Option<String>,
/// The session recorded a `Stop`.
@@ -179,6 +247,8 @@ pub struct SessionDigest {
prompt_count: usize,
/// Completed calls per tool name, keyed for stable ordering.
tool_counts: BTreeMap<String, usize>,
+ /// Calls the harness reported as failed.
+ failed_tool_calls: usize,
/// The page title.
title: String,
/// What the handoff and the abrupt-ending note read.
@@ -237,7 +307,7 @@ impl SessionDigest {
// Overflow only with more than 9.2e18 observations: fail
// toward `Lost` at the stamp (an unrepresentable count never
// matches the stamp-time COUNT), never toward a wrong stamp.
- let total = i64::try_from(snapshot.kind_summary()?.total).unwrap_or(i64::MAX);
+ let total = i64::try_from(digest.observation_count()).unwrap_or(i64::MAX);
Ok((digest, total))
})
.await
@@ -275,6 +345,12 @@ impl SessionDigest {
pub(crate) fn handoff_facts(&self) -> &HandoffFacts {
&self.handoff
}
+
+ /// For tests in other modules; the renderers read the field.
+ #[cfg(test)]
+ pub(crate) fn failed_tool_calls(&self) -> usize {
+ self.failed_tool_calls
+ }
}
fn micros_to_timestamp(micros: i64) -> StoreResult<Timestamp> {
@@ -424,6 +500,15 @@ fn build_digest(
summary.last_post_tool_at,
|obs| Some(obs.title.clone()),
)?,
+ last_failed_tool: match summary.last_failed_tool_at {
+ Some(at) => snapshot.scan(
+ ObservationOrder::Desc,
+ &[ObservationKind::PostToolUse],
+ Some(at),
+ failed_tool_fact,
+ )?,
+ None => None,
+ },
latest_assistant: match summary.last_stop_with_body_at {
Some(at) => snapshot.scan(
ObservationOrder::Desc,
@@ -459,6 +544,7 @@ fn build_digest(
prompt_titles,
prompt_count: prompts.total,
tool_counts,
+ failed_tool_calls: summary.failed_tool_calls,
title,
handoff,
},
@@ -665,6 +751,9 @@ fn session_summary(digest: &SessionDigest) -> String {
)
});
}
+ if digest.failed_tool_calls > 0 {
+ parts.push(format!("{} failed", digest.failed_tool_calls));
+ }
if let (Some(start), Some(end)) = (digest.start_at, digest.end.as_ref())
&& let Some(spent) = format_duration(end.created_at.as_second() - start.as_second())
@@ -778,6 +867,16 @@ fn render_body(session_id: SessionId, digest: &SessionDigest, title: &str) -> St
buf.push('\n');
}
+ // What broke: the count and the newest error text.
+ if digest.failed_tool_calls > 0 {
+ buf.push_str("## Failed tool calls\n\n");
+ buf.push_str(&format!("- **count:** {}\n", digest.failed_tool_calls));
+ if let Some(failed) = &digest.handoff.last_failed_tool {
+ buf.push_str(&format!("- **last:** {}\n", failed.describe()));
+ }
+ buf.push('\n');
+ }
+
buf.push_str("## Raw observations\n\n");
render_raw_observations(&mut buf, digest);
@@ -958,6 +1057,7 @@ impl SessionDigest {
prompt_titles,
prompt_count,
tool_counts,
+ failed_tool_calls: observations.iter().filter(|o| is_failed_tool(o)).count(),
title,
handoff: HandoffFacts::from_observations(observations),
}
@@ -976,6 +1076,7 @@ impl HandoffFacts {
.rev()
.find(|o| o.kind == ObservationKind::PostToolUse)
.map(|o| o.title.clone()),
+ last_failed_tool: observations.iter().rev().find_map(failed_tool_fact),
latest_assistant: observations.iter().rev().find_map(assistant_response),
has_stop: observations.iter().any(|o| o.kind == ObservationKind::Stop),
has_session_end: observations
@@ -1058,6 +1159,12 @@ mod tests {
o
}
+ fn obs_with_body(kind: ObservationKind, title: &str, body: &str) -> Observation {
+ let mut o = obs(kind, title);
+ o.body = body.into();
+ o
+ }
+
#[test]
fn the_summary_states_the_shape_of_the_session() {
let observations = vec![
@@ -1608,6 +1715,158 @@ mod tests {
);
}
+ /// Failed calls are counted in the summary and the newest one is quoted,
+ /// with the tool name when recorded and never its arguments.
+ #[test]
+ fn failed_tool_calls_are_counted_and_the_last_one_is_quoted() {
+ let page_for = |rows: &[Observation]| {
+ synthesize_session_page(
+ WorkspaceId::new(),
+ ProjectId::new(),
+ SessionId::new(),
+ AgentKind::ClaudeCode,
+ rows,
+ )
+ };
+ let observations = vec![
+ obs(ObservationKind::UserPrompt, "make the tests pass"),
+ obs_with_body(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\ntool_call_id: toolu_1\noutcome: error\n---\n\
+ Exit code 1\nError: Cannot find module 'express'\n at require",
+ ),
+ obs_with_body(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\ntool_call_id: toolu_2\noutcome: unknown\n---\n\
+ {\"stdout\":\"42 passing\"}",
+ ),
+ ];
+ let digest = tally_session(&observations);
+ assert_eq!(digest.failed_tool_calls(), 1);
+ assert_eq!(
+ session_summary(&digest),
+ "1 prompt, 2 completed tool calls across Bash, 1 failed."
+ );
+ let page = page_for(&observations);
+ assert!(
+ page.body
+ .contains("## Failed tool calls\n\n- **count:** 1\n"),
+ "{}",
+ page.body
+ );
+ assert!(
+ page.body.contains(
+ "- **last:** Bash: Exit code 1 Error: Cannot find module 'express' at require\n"
+ ),
+ "{}",
+ page.body
+ );
+ assert!(!page.body.contains("toolu_1"), "{}", page.body);
+
+ // A family label names no tool; a header-only body still counts.
+ let bare = vec![
+ obs_with_body(
+ ObservationKind::PostToolUse,
+ "tool file",
+ "tool_family: file\noutcome: error\n---\nENOENT: no such file",
+ ),
+ obs_with_body(
+ ObservationKind::PostToolUse,
+ "tool unknown",
+ "tool_family: unknown\nmcp_server: aim\nmcp_tool: memory_query\noutcome: error",
+ ),
+ ];
+ let digest = tally_session(&bare);
+ assert_eq!(digest.failed_tool_calls(), 2);
+ assert_eq!(
+ digest
+ .handoff_facts()
+ .last_failed_tool
+ .as_ref()
+ .map(FailedToolFact::describe),
+ Some("(no error text captured)".to_string())
+ );
+ assert_eq!(
+ session_summary(&digest),
+ "2 completed tool calls, 2 failed."
+ );
+ let page = page_for(&bare);
+ assert!(
+ page.body.contains("- **last:** (no error text captured)\n"),
+ "{}",
+ page.body
+ );
+
+ // Control: no failures, nothing added.
+ let fine = vec![obs_with_body(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\noutcome: unknown\n---\nok",
+ )];
+ let digest = tally_session(&fine);
+ assert_eq!(digest.failed_tool_calls(), 0);
+ assert!(digest.handoff_facts().last_failed_tool.is_none());
+ assert_eq!(
+ session_summary(&digest),
+ "1 completed tool call across Bash."
+ );
+ let page = page_for(&fine);
+ assert!(!page.body.contains("Failed tool calls"), "{}", page.body);
+ }
+
+ /// Adversarial: the marker is read from the header only, so a tool output
+ /// that echoes a stored body is not a failure. A long error is capped.
+ #[test]
+ fn an_outcome_marker_inside_tool_output_is_not_a_failure() {
+ let echoed = obs_with_body(
+ ObservationKind::PostToolUse,
+ "tool non-file: Bash",
+ "tool_family: non-file\noutcome: unknown\n---\n\
+ tool_family: file\noutcome: error\n---\nquoted from a page\noutcome: error",
+ );
+ let prompt = obs_with_body(
+ ObservationKind::UserPrompt,
+ "why outcome: error",
+ "tool_family: file\noutcome: error\n---\nnot a tool row",
+ );
+ let digest = tally_session(&[prompt, echoed]);
+ assert_eq!(digest.failed_tool_calls(), 0);
+ assert!(digest.handoff_facts().last_failed_tool.is_none());
+
+ let long = obs_with_body(
+ ObservationKind::PostToolUse,
+ "Bash",
+ &format!(
+ "tool_family: non-file\noutcome: error\n---\n{}",
+ "e ".repeat(400)
+ ),
+ );
+ let fact = failed_tool_fact(&long).expect("a failed call");
+ assert!(
+ fact.error.len() <= FAILED_TOOL_EXCERPT_BYTES,
+ "{}",
+ fact.error
+ );
+ assert!(fact.error.ends_with('…'));
+ assert_eq!(fact.describe(), format!("Bash: {}", fact.error));
+ }
+
+ /// The store and the router spell the marker in different crates; keep
+ /// them equal.
+ #[test]
+ fn the_failed_outcome_marker_is_the_one_the_router_writes() {
+ assert_eq!(
+ format!(
+ "{}{}",
+ ai_memory_core::TOOL_OUTCOME_LINE_PREFIX,
+ crate::capture_policy::ToolOutcome::Error.as_str()
+ ),
+ FAILED_TOOL_OUTCOME_LINE
+ );
+ }
+
#[test]
fn pre_only_tool_calls_are_not_counted() {
// A PreToolUse without a matching PostToolUse (cancelled / crashed
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 10ece2c6..7896fe70 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -13,10 +13,12 @@ use std::str::FromStr;
use std::sync::Arc;
use ai_memory_core::{
- AgentKind, AgentMessage, AutoImproveProposalId, AutoImproveRunId, Handoff, HandoffContent,
- HandoffId, HandoffLifecycle, HandoffOrigin, HandoffScope, HandoffState, IdentityKey,
- ManagedRunId, MessageBox, Observation, ObservationId, ObservationKind, OwnerFilter, PageId,
- PagePath, ProjectId, SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,
+ AgentKind, AgentMessage, AutoImproveProposalId, AutoImproveRunId, FAILED_TOOL_OUTCOME_LINE,
+ Handoff, HandoffContent, HandoffId, HandoffLifecycle, HandoffOrigin, HandoffScope,
+ HandoffState, IdentityKey, ManagedRunId, MessageBox, Observation, ObservationId,
+ ObservationKind, OwnerFilter, PageId, PagePath, ProjectId, SessionId,
+ TOOL_BODY_HEADER_MAX_CHARS, TOOL_BODY_SEPARATOR, User, UserId, WorkspaceId, WorkstreamEvent,
+ WorkstreamId,
};
use jiff::Timestamp;
use parking_lot::Mutex;
@@ -14676,6 +14678,25 @@ pub struct SessionKindSummary {
pub last_post_tool_at: Option<i64>,
/// Newest `user-prompt`.
pub last_prompt_at: Option<i64>,
+ /// `post-tool-use` rows whose header ends in [`FAILED_TOOL_OUTCOME_LINE`].
+ pub failed_tool_calls: usize,
+ /// Newest such row.
+ pub last_failed_tool_at: Option<i64>,
+}
+
+/// The hooks crate's `is_failed_tool` in SQL: within the first
+/// [`TOOL_BODY_HEADER_MAX_CHARS`] characters, the header is the text before
+/// the first separator (`?7`) or all of it, and `substr(header, -len) = ?8`
+/// is `ends_with(marker)`. An `outcome: error` line inside a tool's output
+/// never counts, and no output excerpt is scanned.
+fn failed_tool_sql() -> String {
+ format!(
+ "substr(CASE WHEN instr(substr(body, 1, {head}), ?7) > 0 \
+ THEN substr(body, 1, instr(substr(body, 1, {head}), ?7) - 1) \
+ ELSE substr(body, 1, {head}) END, -{len}) = ?8",
+ head = TOOL_BODY_HEADER_MAX_CHARS,
+ len = FAILED_TOOL_OUTCOME_LINE.len(),
+ )
}
/// Row count and `created_at` span of one session's observations, in one
@@ -14759,6 +14780,7 @@ impl SessionObservationSnapshot<'_> {
/// # Errors
/// Propagates any SQL error.
pub fn kind_summary(&self) -> StoreResult<SessionKindSummary> {
+ let failed = failed_tool_sql();
let sql = format!(
"SELECT COUNT(*), \
COALESCE(SUM(kind = ?2), 0), \
@@ -14768,7 +14790,9 @@ impl SessionObservationSnapshot<'_> {
MAX(CASE WHEN kind = ?5 THEN created_at END), \
MAX(CASE WHEN kind = ?5 AND body <> '' THEN created_at END), \
MAX(CASE WHEN kind = ?6 THEN created_at END), \
- MAX(CASE WHEN kind = ?2 THEN created_at END) \
+ MAX(CASE WHEN kind = ?2 THEN created_at END), \
+ COALESCE(SUM(kind = ?6 AND {failed}), 0), \
+ MAX(CASE WHEN kind = ?6 AND {failed} THEN created_at END) \
FROM observations WHERE session_id = ?1"
);
let summary = self.conn.query_row(
@@ -14780,6 +14804,8 @@ impl SessionObservationSnapshot<'_> {
ObservationKind::SessionEnd.as_str(),
ObservationKind::Stop.as_str(),
ObservationKind::PostToolUse.as_str(),
+ TOOL_BODY_SEPARATOR,
+ FAILED_TOOL_OUTCOME_LINE,
],
|row| {
Ok(SessionKindSummary {
@@ -14792,6 +14818,8 @@ impl SessionObservationSnapshot<'_> {
last_stop_with_body_at: row.get(6)?,
last_post_tool_at: row.get(7)?,
last_prompt_at: row.get(8)?,
+ failed_tool_calls: usize::try_from(row.get::<_, i64>(9)?).unwrap_or(usize::MAX),
+ last_failed_tool_at: row.get(10)?,
})
},
)?;
diff --git a/docs/design-marketplace-plugins.md b/docs/design-marketplace-plugins.md
index e28de8a5..f23f5dee 100644
--- a/docs/design-marketplace-plugins.md
+++ b/docs/design-marketplace-plugins.md
@@ -560,8 +560,9 @@ passed `claude plugin validate --strict` in the prototype.
}
```
-`plugins/claude-code/hooks/hooks.json`, the same nine events and empty
-matchers `install-hooks` writes today:
+`plugins/claude-code/hooks/hooks.json`, the same events and empty matchers
+`install-hooks` writes today (`PostToolUseFailure` was added later in the same
+shape):
```json
{
diff --git a/docs/install.md b/docs/install.md
index 5408c7a6..258f1d56 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -308,6 +308,16 @@ configure ai-memory@ai-memory`:
`install-mcp`, `install-skills`) to add them anyway.
- Folderless sessions (a desktop scratch workspace with no project folder)
are not captured through the plugin.
+- Ten events are wired: `SessionStart`, `UserPromptSubmit`, `PreToolUse`,
+ `PostToolUse`, `PostToolUseFailure`, `PreCompact`, `Stop`, `SessionEnd`,
+ `SubagentStart` and `SubagentStop`. Claude Code fires `PostToolUseFailure`
+ *instead of* `PostToolUse` when a tool fails (a non-zero exit, a thrown
+ error, an MCP error result). The observation records `outcome: error` and
+ the error text, bounded like any tool excerpt and never the tool's
+ arguments; the session page counts failed calls and quotes the newest one;
+ the automatic handoff adds a `Last failed tool call` line. An install made
+ before this fix has nine events; re-run `ai-memory install-hooks --agent
+ claude-code --apply` (or `ai-memory setup`) to add the tenth.
- Factory Droid can install this plugin through its Claude marketplace
fallback. Its events are recorded as `droid`, and when `install-hooks
--agent droid` hooks deliver the same event (`~/.factory/hooks.json`, or
@@ -1930,9 +1940,9 @@ The events are configured with PascalCase names (`SessionStart`,
`PreToolUse`, …), which makes Copilot send the VS Code/Claude-compatible
snake_case payload (`session_id`, `cwd`, `tool_name`, `tool_input`,
`tool_result`), so ai-memory's existing extraction applies and native commands
-enforce `[capture] ignore_paths`. Ten events are wired: Claude Code's nine plus
-`PostToolUseFailure`, which Copilot fires instead of `PostToolUse` when a tool
-errors. Entries sit directly in each event array with no `matcher`: Copilot
+enforce `[capture] ignore_paths`. Ten events are wired, the same as Claude
+Code's, including `PostToolUseFailure`, which Copilot fires instead of
+`PostToolUse` when a tool errors. Entries sit directly in each event array with no `matcher`: Copilot
rejects `matcher` on `SessionStart`, `Stop`, `SessionEnd`, and the subagent
events, and omitting it elsewhere means "every invocation". Tool output is
read from `tool_result.text_result_for_llm`.
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index 3b69fa10..8afc76b1 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -395,8 +395,8 @@ write one, keeping in mind that `.github/mcp.json` is meant to be committed,
so it should not carry a bearer token. `install-hooks --agent copilot-cli`
run without `--server-url` reads the URL and token back from this entry.
-The hook installer wires Claude Code's nine events plus `PostToolUseFailure`
-with PascalCase names, which makes Copilot send its VS Code/Claude-compatible
+The hook installer wires the same ten events as Claude Code, `PostToolUseFailure`
+included, with PascalCase names, which makes Copilot send its VS Code/Claude-compatible
payload; native installs spool events locally and enforce capture exclusions. The
`SessionStart` hook delivers the prior session's handoff: Copilot reads a
top-level `additionalContext` from `SessionStart` stdout (not Claude Code's
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 6e86a21a..91a2d70c 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -119,7 +119,7 @@ the legitimate restricted-project control and the failed-query cases.
| 11j | Offline recovery journal and transcript replay | `ai-memory-cli/src/commands/recovery.rs` keeps bounded locators, ordered semantic transcript digests, pre-launch cursors and persistent correlated-delivery/loss evidence in an atomic journal, refuses a symlinked data dir and any symlinked component inside it (ancestors above the data dir are trusted, so macOS `/var` → `/private/var` works), sanitizes/caps failure reasons, and bounds each replay plus the whole pass; `hook_spool` coordinates enqueue and quarantine with short filesystem locks, canonically resolves partial scope from the recorded cwd, bounds per-file reads and current global occupancy across the main spool and recovery directories, sweeps completed tombstones, and holds correlated events outside drain until replay succeeds or restores them on failure; degraded resumes use `ai-memory-workstream`'s adapter-validated delta export, whose blocking parse and baseline scans are capped by record, event-count, source-byte and serialized-byte totals (a record over the per-record cap is discarded through its newline in 64 KiB chunks that count toward the source-byte total, and moves the cursor and prefix hash only once complete, identically in both scans, #1613); `backfill::import_exact_session` chunks by item and byte limits and requires per-item durable acknowledgements; `run.rs` journals every session launch, including explicit spool-only evidence for unsupported exporters, and journals a resumed export only after capturing its exact pre-launch cursor; `workstream.rs` `/recover/finish` retains owner/project authorization, rejects superseded runs, and validates a finished retry by durable transcript/native/cursor/exit identity without regenerating its checkpoint; validated recovery ingest keys bind session, agent, event kind and sanitized event identity until session purge | `transcript.rs` `persisted_baseline_exports_only_offline_append_and_rejects_rewrite`, parser/baseline cap and ordered-semantic digest tests, `an_oversized_record_is_skipped_only_once_it_is_complete`, `kimi_baseline_and_export_agree_on_the_prefix_across_a_skipped_record`, `discarding_an_oversized_record_counts_toward_the_source_byte_cap`; CLI `run_offline.rs` real degraded spool-only and overlap/idempotency tests; `recovery.rs` `spool_only_without_correlated_evidence_never_auto_clears`, `a_dropped_spool_event_stays_lost_on_the_next_empty_pass`, loss/time-budget tests, `symlinked_journal_and_ancestor_are_refused`, `a_symlinked_ancestor_of_the_data_dir_is_trusted`, `a_symlink_inside_a_data_dir_under_a_symlinked_ancestor_is_refused`; `hook_spool.rs` partial-scope late enqueue, completion-race, occupancy churn/active-cap, bounded-read and tombstone-sweep tests, plus interval isolation (`completed_tombstone_keeps_a_later_resume_of_the_same_session` proves a post-interval resume hook is delivered, `completing_one_recovery_interval_leaves_the_other_intervals_entries_intact` proves one interval's completion never consumes another's evidence and ambiguous entries fail closed into the main spool); `backfill.rs` `two_sequential_recovery_intervals_on_one_resumed_session_replay_exactly_once` proves the second interval's content and session-end are stored with end-of-session effects while reruns stay pure replays; `transcript.rs` `an_oversized_first_record_is_skipped_by_session_listing_caps` proves the first-record byte caps bite before allocation; store `insert_observation_ingest_dedups_on_key` rejects cross-session and changed-event preclaims; hooks `expired_run_recovery_is_owner_only_and_refuses_superseded_runs` proves changed transcript refusal and changed-checkpoint no-op | STRONG on Unix integration coverage; Unix lock opens use no-follow and atomic replacement rechecks the destination. Windows owner-only ACL/reparse and lock semantics require the PR `windows` lane |
| 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 |
| 11k | Server-side ingest drop list: tool id/name lists (#1241) and whole event kinds (`[ingest] drop_events`) | `ai-memory-hooks/src/drop_list.rs` `IngestDropList`: `matches` for the tool lists (a tool-call id by prefix, a tool name exactly) and `matches_event_kind` for the whole kinds (every `[ingest] drop_events` value parsed with the typed `HookEvent::parse`; `session-start`/`session-end` and the `other` bucket rejected), both validated once in `Config::load` (tool lists: at most 64 entries of 128 printable characters each). Checked in `router.rs` `admit_hook` and the `handle_hook_batch` loop after the subagent exclusion (`should_drop_subagent`) and before the rate limiter, ingest semaphore, sanitizer, and storage, so a marked subagent event seeds the tracking set its unmarked tail is dropped against even when its tool id, tool name, or event kind is listed. The tool lists match only tool events and are read through the per-agent mapping `capture_policy::tool_payload_fields` that tool metadata uses. A drop answers 202 and counts as `dropped_by_policy`; the matched value is never logged | tool lists: `router.rs` `the_ingest_drop_list_drops_before_any_capacity_is_spent`, `the_ingest_drop_list_applies_to_hook_batches`, `marked_tool_policy_drops_seed_subagent_tracking_before_single_ingress_matching`, and `marked_tool_policy_drops_seed_subagent_tracking_before_batch_matching` cover capacity, batch acknowledgements, id-prefix and exact-name seeding order, unmarked tails, and stored controls; `drop_list.rs` unit tests cover bounds, exact matching, and each agent's native fields. Whole kinds: `router.rs` `the_ingest_drop_events_drops_the_named_kind_and_keeps_the_rest`, `the_ingest_drop_events_drops_before_any_capacity_is_spent`, `the_ingest_drop_events_consumes_no_rate_budget`, `the_ingest_drop_events_batch_reports_per_index_outcomes_and_only_stores_the_kept`, `the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail`, `the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail_in_batches`, and `a_marked_event_of_a_dropped_kind_still_seeds_subagent_tracking`; `drop_list.rs` `drop_events_*` tests cover typed matching and rejected state/unknown kinds. Moving any matcher before subagent exclusion fails its single/batch tail tests; removing either batch matcher fails its batch contract | STRONG. The list applies to every project on the server; it narrows what is stored and never widens access |
-| 11l | Marketplace plugin front door: a plugin-launched event gets exactly the native hook's capture policy, scope and server routing, is captured once beside settings-file hooks, and sends nothing without the binary (#1166) | `plugins/*/scripts/ai-memory-hook` (rendered from `crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh` by `render_plugins.rs`) has no capture logic: it only finds the binary (an `ai_memory_bin` option is honoured only as an absolute path, so a checkout cannot plant a relative one) and runs `ai-memory hook` with `AI_MEMORY_HOOK_ORIGIN=<agent>-plugin`, `hook` first so the Docker wrapper routes it, omitting `--server-url` when the option is empty (a pre-3.0 binary's usage error, exit 2 before it reads stdin, is retried once against the default local server with a stderr hint), and without a binary drains stdin, prints `{}` (guidance on `session-start` only) and exits 0; `hook.rs` `is_dropped_plugin_copy` + `plugin_origin.rs` `drops_plugin_event` drop a plugin copy when the user `settings.json` (honouring `CLAUDE_CONFIG_DIR`) or the checkout's `.claude/settings.local.json` carries an ai-memory hook for the same event (`install_hooks::hooks_file_delivers_ai_memory_event`); a Droid-launched copy (`droid-plugin`) is checked against the one file Droid reads hooks from (`~/.factory/hooks.json`, else the `hooks` key of `~/.factory/settings.json`); a Muse-launched copy (`muse-plugin`, recognized by `MUSE_PLUGIN_ID` with `MUSE_SESSION_ID`) is checked against the `hooks` key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, and its subagent events are dropped; both drop a folderless session (no `cwd`, or a Claude desktop `scratch-workspaces` cwd); Codex plugin events are never de-duplicated (an untrusted settings hook is skipped silently, so dropping could lose the event); the drift test keeps every plugin hook on the native path (no `hooks/<agent>/*.sh`, no credential in any plugin file) | CLI `tests/suite/plugins.rs` through the committed launcher and the real binary: `ignore_paths_hold_through_the_plugin` (ignored path never spooled; public-file control kept), `allowlist_mode_holds_through_the_plugin` (unmarked checkout emits nothing, prompts included; marked control captured), `marker_scope_routes_plugin_events`, `server_profiles_route_plugin_events` (profile URL and token, never the plugin's URL), `a_settings_hook_for_the_same_event_drops_the_plugin_copy` (user and project settings; unwired-event and no-settings controls), `a_droid_hook_for_the_same_event_drops_the_droid_plugin_copy` (Droid `hooks.json`; no-Droid-hook, Claude-settings-only, unwired-event and folderless controls), `a_muse_hook_for_the_same_event_drops_the_muse_plugin_copy` (Muse `settings.json`; no-Muse-hook, Claude-settings-only and unwired-event controls; subagent and folderless events dropped), `plugin_origin.rs` `muse_plugin_copy_is_dropped_when_muse_settings_hooks_deliver_the_event` (a matcher-narrowed hook does not count) and `test_plugin_launcher.sh` (an inherited `MUSE_SESSION_ID` without `MUSE_PLUGIN_ID` stays `claude-code`), `folderless_sessions_are_not_captured_through_the_plugin`, `without_a_binary_nothing_is_sent_and_the_agent_is_not_blocked`, `foreign_hosts_are_attributed_or_ignored`, `committed_plugins_match_the_renderer`, `plugin_tree_carries_no_credentials`; `plugin_origin.rs` unit tests (`codex_plugin_events_are_never_deduplicated_against_settings`, `droid_settings_hooks_count_only_while_hooks_json_is_absent`, `only_a_catch_all_matcher_suppresses_the_plugin_copy`: a settings hook narrowed by a matcher never drops the plugin copy); `hook.rs` `plugin_copy_is_dropped_only_with_the_plugin_origin`; `tests/hooks/test_plugin_launcher.sh` (a relative `ai_memory_bin` planted in the checkout is never run; PATH control); `tests/e2e/claude_plugin_smoke.py` (real `claude -p`: settings hook plus plugin give one `user-prompt`) | STRONG. Verified 2026-10-13: removing the `is_dropped_plugin_copy` guard fails the de-duplication and folderless tests (and the smoke reports `user-prompt x2`); disabling the native `Drop` disposition or the allowlist gate fails the `ignore_paths` and allowlist tests through the launcher. Not covered: tool events from a live model turn (no credential in CI), Windows Git Bash, Cowork and the desktop Code tab (see `docs/design-marketplace-plugins.md`) |
+| 11l | Marketplace plugin front door: a plugin-launched event gets exactly the native hook's capture policy, scope and server routing, is captured once beside settings-file hooks, and sends nothing without the binary (#1166) | `plugins/*/scripts/ai-memory-hook` (rendered from `crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh` by `render_plugins.rs`) has no capture logic: it only finds the binary (an `ai_memory_bin` option is honoured only as an absolute path, so a checkout cannot plant a relative one) and runs `ai-memory hook` with `AI_MEMORY_HOOK_ORIGIN=<agent>-plugin`, `hook` first so the Docker wrapper routes it, omitting `--server-url` when the option is empty (a pre-3.0 binary's usage error, exit 2 before it reads stdin, is retried once against the default local server with a stderr hint), and without a binary drains stdin, prints `{}` (guidance on `session-start` only) and exits 0; `hook.rs` `is_dropped_plugin_copy` + `plugin_origin.rs` `drops_plugin_event` drop a plugin copy when the user `settings.json` (honouring `CLAUDE_CONFIG_DIR`) or the checkout's `.claude/settings.local.json` carries an ai-memory hook for the same event (`install_hooks::hooks_file_delivers_ai_memory_event`), the settings event taken from the payload's `hook_event_name` when two settings events share a wire event (`PostToolUse`/`PostToolUseFailure`), so settings wiring only the success event never silence a failure copy; a Droid-launched copy (`droid-plugin`) is checked against the one file Droid reads hooks from (`~/.factory/hooks.json`, else the `hooks` key of `~/.factory/settings.json`); a Muse-launched copy (`muse-plugin`, recognized by `MUSE_PLUGIN_ID` with `MUSE_SESSION_ID`) is checked against the `hooks` key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, and its subagent events are dropped; both drop a folderless session (no `cwd`, or a Claude desktop `scratch-workspaces` cwd); Codex plugin events are never de-duplicated (an untrusted settings hook is skipped silently, so dropping could lose the event); the drift test keeps every plugin hook on the native path (no `hooks/<agent>/*.sh`, no credential in any plugin file) | CLI `tests/suite/plugins.rs` through the committed launcher and the real binary: `ignore_paths_hold_through_the_plugin` (ignored path never spooled; public-file control kept), `allowlist_mode_holds_through_the_plugin` (unmarked checkout emits nothing, prompts included; marked control captured), `marker_scope_routes_plugin_events`, `server_profiles_route_plugin_events` (profile URL and token, never the plugin's URL), `a_settings_hook_for_the_same_event_drops_the_plugin_copy` (user and project settings; unwired-event and no-settings controls), `a_droid_hook_for_the_same_event_drops_the_droid_plugin_copy` (Droid `hooks.json`; no-Droid-hook, Claude-settings-only, unwired-event and folderless controls), `a_muse_hook_for_the_same_event_drops_the_muse_plugin_copy` (Muse `settings.json`; no-Muse-hook, Claude-settings-only and unwired-event controls; subagent and folderless events dropped), `plugin_origin.rs` `muse_plugin_copy_is_dropped_when_muse_settings_hooks_deliver_the_event` (a matcher-narrowed hook does not count), `a_plugin_failure_copy_is_dropped_only_when_settings_deliver_the_failure_event` (settings wiring only `PostToolUse` keep the plugin's failure copy; controls: the success copy, no `hook_event_name`, both events wired) and `test_plugin_launcher.sh` (an inherited `MUSE_SESSION_ID` without `MUSE_PLUGIN_ID` stays `claude-code`), `folderless_sessions_are_not_captured_through_the_plugin`, `without_a_binary_nothing_is_sent_and_the_agent_is_not_blocked`, `foreign_hosts_are_attributed_or_ignored`, `committed_plugins_match_the_renderer`, `plugin_tree_carries_no_credentials`; `plugin_origin.rs` unit tests (`codex_plugin_events_are_never_deduplicated_against_settings`, `droid_settings_hooks_count_only_while_hooks_json_is_absent`, `only_a_catch_all_matcher_suppresses_the_plugin_copy`: a settings hook narrowed by a matcher never drops the plugin copy); `hook.rs` `plugin_copy_is_dropped_only_with_the_plugin_origin`; `tests/hooks/test_plugin_launcher.sh` (a relative `ai_memory_bin` planted in the checkout is never run; PATH control); `tests/e2e/claude_plugin_smoke.py` (real `claude -p`: settings hook plus plugin give one `user-prompt`) | STRONG. Verified 2026-10-13: removing the `is_dropped_plugin_copy` guard fails the de-duplication and folderless tests (and the smoke reports `user-prompt x2`); disabling the native `Drop` disposition or the allowlist gate fails the `ignore_paths` and allowlist tests through the launcher. Not covered: tool events from a live model turn (no credential in CI), Windows Git Bash, Cowork and the desktop Code tab (see `docs/design-marketplace-plugins.md`) |
| 11m | The server never opens a filesystem path named in a hook payload | `ai-memory-hooks/src/payload.rs` `HookEnvelope::from_query_and_body` (run by `/hook` and every `/hook/batch` item) only reads the posted JSON; Antigravity step-log enrichment (`antigravity.rs` `enrich_antigravity_step_output`, which opens `<artifactDirectoryPath or transcriptPath dir>/.system_generated/steps/<stepIdx>/output.txt`) runs only client-side in `ai-memory-cli/src/commands/hook.rs` against the client's own home, and the server stores whatever `tool_response` the client sent | `router.rs` `a_hook_payload_cannot_make_the_server_read_its_own_disk` (an Antigravity `PostToolUse` batch naming a server-only directory through `artifactDirectoryPath` and through `transcriptPath`; no stored observation or file contains the server-side sentinel); `payload.rs` `envelope_parsing_never_reads_a_payload_named_antigravity_artifact` and `antigravity_post_tool_use_renders_client_enriched_output` (control: client-supplied output still rendered) | STRONG. Both adversarial tests fail with the server-side enrichment call reinstated (the sentinel file content is stored and readable through search) |
| 11n | Opt-in tool names (`[ingest] record_tool_names`) name only a kept call and never carry its arguments | `ai-memory-hooks/src/capture_policy.rs` `recorded_tool_name` keeps the adapter tool name only when it is at most 64 `[A-Za-z0-9_-]`, and Claude Code's `skill` / `subagent_type` only when at most 128 `[A-Za-z0-9_.:-]`, refusing free text whole; `payload.rs` `HookEnvelope::record_tool_name` renames only a title that is still the bare `tool <family>` label; `router.rs` calls it after `inspect_capture_envelope`, and `metadata_envelope` / `metadata_only_protocol_envelope` clear the recorded name, so a call the client stripped, or a shell call the server strips under an invalid marker, stays unnamed | `router.rs` `record_tool_names_names_kept_calls_and_never_metadata_only_ones` (a kept Bash call is named; a client-stripped file call and a server-stripped invalid-marker shell call whose payload still says `Bash` are not; no argument text is stored) fails with both the title guard and the two clears removed, with the control `tool_calls_stay_unnamed_when_record_tool_names_is_off`; `payload.rs` `record_tool_name_refuses_free_text_names_and_descriptors` | STRONG |
| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `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`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile (`http_client.rs` `is_loopback_url`, shared by every caller, decides loopback from the host `reqwest` parses and refuses any URL carrying user information); `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `mcp_bridge.rs` `bridge_bearer` sends a configured bearer, else the hook key stored in `<data_dir>/auth-token`, else the discovered loopback root token (`AuthSettings::configured_bearer_token` leaves discovery out, so a server+client host never sends root over a stored user key), and the fallback is in the bridge only (`Config::load` never reads that file, so `serve` neither requires nor accepts it); `install_mcp.rs` `store_bridge_key` stores an explicit `--auth-token` there for the Claude Code and Muse bridge entries on `--apply` and writes the entry with `--data-dir` and no key, keeping the key inline when a configured bearer would win, a different key is stored, the hooks use OIDC, the store fails or the Docker helper runs; `uninstall.rs` keeps the stored key on `--only hooks` while `install_mcp::bridge_entry_remains`; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`, `setup.rs` (runs `init`, adopts the minted token in memory through `adopt_token_file`, and calls the installers with no explicit token; the rendered user unit carries none; `user_service.rs` `is_rendered_by_setup` lets `uninstall` stop and delete only a unit carrying `setup`'s identity line whose SHA-256 still matches, never a hand-written or edited one); `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `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; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, a remote host behind loopback-looking user information, `default` profile, env token); `http_client.rs` `loopback_url_is_decided_by_the_parsed_host` (user-information, fragment and query forms, look-alike domains, `localhost.`, `0.0.0.0` and IPv4-mapped IPv6 refused; `127.0.0.0/8`, `[::1]` and `localhost` in any case accepted); `mcp_bridge.rs` `discovered_root_never_leaves_loopback_but_the_stored_user_key_follows_the_entry` (adversarial: remote and user-information `--server-url` forms get no root key; control: an unnamed loopback server does); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `config.rs` `config_load_never_adopts_the_stored_hook_key` (adversarial: a stored hook key leaves the loaded bearer empty, so `serve` on that data dir neither requires nor accepts it; control: a `bearer_token_file` naming the same file is adopted); `mcp_bridge.rs` `bridge_bearer_puts_the_stored_hook_key_below_a_configured_bearer` (a configured bearer wins, a blank one does not), `a_stored_user_key_outranks_the_discovered_root_token` (adversarial: discoverable loopback root plus a stored key sends the stored key; control: discovery alone still sends root); `install_mcp.rs` `an_explicit_key_for_a_bridge_is_stored_instead_of_written_inline` (Claude Code and Muse entries carry no key and name the data dir, the stored pair is the hooks' format; controls keeping the key inline and storing nothing: print path, configured bearer, a different stored key, OIDC hooks, Docker helper, HTTP entry); `removal.rs` `an_explicit_bridge_key_is_stored_and_outlives_only_hooks_removal`; `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential`; `setup_e2e.rs` `setup_installs_wires_is_idempotent_and_uninstall_removes_its_unit` (one `setup --yes` in a fresh temp home: the token is in no file under the home but the token file and the two hook credential files, not in the user unit and not in `setup`'s output; the self-check's `memory_status` and a hook event authenticate through the file; `uninstall` then disables and deletes the unit once and a second `uninstall` calls nothing), `uninstall_leaves_a_unit_it_did_not_write` (adversarial: the packaged unit copied by hand is kept, no `systemctl` call); `user_service.rs` `a_foreign_or_edited_unit_is_left_alone`, `rendered_units_carry_an_identity_that_survives_only_unedited` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with `Config::load` adopting the stored hook key, without the bridge fallback, with discovery counted as a configured bearer, or with `install-mcp` never storing the key, the matching new test fails; with `setup` handing the token to `install-mcp` its scan finds it in `.claude.json`; with `is_rendered_by_setup` accepting any unit, the foreign-unit tests fail; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients |
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 4c938b40..bacd6a90 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -16,7 +16,7 @@
| macOS | Supported | Workspace tests run in CI; tagged releases publish native `ai-memory-macos-aarch64.tar.gz` and `ai-memory-macos-x86_64.tar.gz` binaries, which include a per-user launchd agent. The native binary is the recommended path on Apple Silicon. A source-built menu bar app (`companions/ai-memory-macos`) bundles that binary, starts the LaunchAgent, and opens `/web` and `ai-memory status` — README quick-start and [`docs/macos.md`](macos.md) Scenario D. |
| Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. |
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Native `ai-memory upgrade` is supported for writable x86_64 zip installs (checksum-verified zip + rename-aside self-replace + sibling `hooks/` refresh). Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](windows.md). |
-| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge; on a token-file install (every fresh `init`) the session-aware bridge entry is automatic. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). A prompt starting with `reload context` receives a compaction recap through `UserPromptSubmit` `additionalContext` (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
+| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. Ten events are wired, `PostToolUseFailure` included: Claude Code fires it instead of `PostToolUse` when a tool fails, and the observation records `outcome: error` with the bounded error text, so failures reach search, consolidation and the handoff's `Last failed tool call` line. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge; on a token-file install (every fresh `init`) the session-aware bridge entry is automatic. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). A prompt starting with `reload context` receives a compaction recap through `UserPromptSubmit` `additionalContext` (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. The same hooks, MCP tools and skills also ship as a marketplace plugin (ai-memory 3.0 or later; see [`install.md`](install.md#marketplace-plugins)). `SessionEnd` is wired since Codex CLI 0.145.0 (openai/codex#33895), so finished sessions get an automatic end-of-session summary/handoff; on older Codex the event is inert and `ai-memory finalize-session --agent codex` is the fallback. Managed runs (`ai-memory run codex`) recover when Codex's shared daemon reports a stale run id, provided exactly one live run matches the authorized project, checkout, and operator; ambiguous matches fail closed. `--no-daemon` remains available as an isolation and diagnostic option (see [`docs/managed-workstreams.md`](managed-workstreams.md)). Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default) — Codex's `Stop` payload carries `last_assistant_message`, same as Claude Code. A prompt starting with `reload context` receives a compaction recap as `UserPromptSubmit` developer context, capped at 6,000 chars (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn; an interactive session launched with `ai-memory run command-code` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run command-code` adds exact v3 native-session resume and visible-event import; experimental unsandboxed Mods remain excluded. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
@@ -39,7 +39,7 @@
| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |
| Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions, unless it is an interactive session launched with `ai-memory run kiro`, which finalizes it automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. |
| Pool | Hooks-only | Poolside Agent CLI (`pool`). Lifecycle-hook capture via `install-hooks --agent pool` (alias `poolside`): Pool reads project-scoped hooks from the repo-root `.poolside/settings.yaml`, so ai-memory stages the scripts and prints a ready-to-paste `hooks:` snippet rather than writing committed project files; native commands enforce capture exclusions. Five Claude-shaped events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`) and no true session-end — `Stop` is a turn boundary, so run `ai-memory finalize-session --agent pool` after the final turn. `SessionStart` stdout injection is not demonstrated, so capture works but handoff injection does not — recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. No first-party `install-mcp` client and no managed workstream (`ai-memory run pool`) are claimed: Pool's native session-store contract is not demonstrated (see [`docs/managed-harness-contributions.md`](managed-harness-contributions.md)). Verified against Poolside CLI v1.0.16. |
-| GitHub Copilot CLI | Supported | MCP config (`install-mcp --client copilot-cli` → `$COPILOT_HOME/mcp-config.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks: `install-hooks --agent copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (`COPILOT_HOME` defaults to `~/.copilot`). Configured with PascalCase event names, so Copilot sends the VS Code/Claude-compatible payload (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_result`) and native commands enforce capture exclusions; 10 events, Claude Code's nine plus `PostToolUseFailure`. Entries are flat with no `matcher`, because Copilot rejects it on `SessionStart`/`Stop`/`SessionEnd` and subagent events. The `SessionStart` hook delivers the prior session's handoff through Copilot's top-level `additionalContext`. Routing: Copilot CLI loads `AGENTS.md`, and `install-skills --agent copilot-cli` (or `install-instructions --skills-agent copilot-cli`) writes the managed Agent Skills to `.github/skills` (project) or `$COPILOT_HOME/skills` (global); `memory_install_self_routing` returns the same `copilot_cli` hints. `--scope project` is intentionally unsupported: Copilot's repository hook files (`.github/hooks/*.json`) are versioned and shared with the team and the cloud agent, so they cannot carry this machine's absolute executable and data-dir paths. `ai-memory run copilot` (alias `copilot-cli`) adds managed workstream resume: a generated `--session-id` for a fresh session, `--resume=<id>` to return, and visible-history import from `$COPILOT_HOME/session-state/<uuid>/events.jsonl` (see [`docs/managed-workstreams.md`](managed-workstreams.md)). The bare `--client copilot` alias of `install-mcp` keeps meaning VS Code Copilot. |
+| GitHub Copilot CLI | Supported | MCP config (`install-mcp --client copilot-cli` → `$COPILOT_HOME/mcp-config.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks: `install-hooks --agent copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (`COPILOT_HOME` defaults to `~/.copilot`). Configured with PascalCase event names, so Copilot sends the VS Code/Claude-compatible payload (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_result`) and native commands enforce capture exclusions; the same 10 events as Claude Code, `PostToolUseFailure` included. Entries are flat with no `matcher`, because Copilot rejects it on `SessionStart`/`Stop`/`SessionEnd` and subagent events. The `SessionStart` hook delivers the prior session's handoff through Copilot's top-level `additionalContext`. Routing: Copilot CLI loads `AGENTS.md`, and `install-skills --agent copilot-cli` (or `install-instructions --skills-agent copilot-cli`) writes the managed Agent Skills to `.github/skills` (project) or `$COPILOT_HOME/skills` (global); `memory_install_self_routing` returns the same `copilot_cli` hints. `--scope project` is intentionally unsupported: Copilot's repository hook files (`.github/hooks/*.json`) are versioned and shared with the team and the cloud agent, so they cannot carry this machine's absolute executable and data-dir paths. `ai-memory run copilot` (alias `copilot-cli`) adds managed workstream resume: a generated `--session-id` for a fresh session, `--resume=<id>` to return, and visible-history import from `$COPILOT_HOME/session-state/<uuid>/events.jsonl` (see [`docs/managed-workstreams.md`](managed-workstreams.md)). The bare `--client copilot` alias of `install-mcp` keeps meaning VS Code Copilot. |
| 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. |
| Meta Muse Code | Supported | MCP config (`install-mcp --client muse`, aliases `muse-code`, `musecode`) + lifecycle hooks (`install-hooks --agent muse`), both merged into `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json` around your own keys, servers and hooks. The writers add the mandatory `"schema_version": 1` when it is absent (without it every `muse` command fails at startup) and never rewrite an existing value. The MCP entry is a stdio `ai-memory mcp-bridge --agent muse` that forwards the `MUSE_SESSION_ID` Muse gives its stdio servers, so Muse is session-aware; it carries `"mode": "optional"` (Muse's default `required` aborts the run when a server cannot start) and the install's `--data-dir`, because Muse starts stdio servers and hooks with a cleared environment. It goes under `mcpServers`, or under the legacy `mcp_servers` when the file already uses it; Muse ignores every MCP server when both maps are present, so `--apply` refuses that file and `doctor` reports it. Hooks run the native `ai-memory hook --event … --agent muse` command (no script bundle) with an empty matcher and a 30-second timeout, and native commands enforce capture exclusions over Muse's `read_file`, `write_file`, `edit_file`, `apply_patch`, `search`, `bash`, `monitor`, `web_fetch` and memory tools; a relative `path` resolves lexically against `cwd`, and Muse's `tool_use_id` is kept as the call id. Eight events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PreCompact`, `Stop`, `SessionEnd`; `SubagentStart`/`SubagentStop` are left out because Muse fires them every turn for its built-in reminder observers. The `SessionStart` hook delivers the prior session's handoff through `hookSpecificOutput.additionalContext`, and Muse's own `SessionEnd` closes the session. Verified offline against Muse Code 1.4.7: hook capture, exclusions, MCP session routing and handoff injection, run end to end in an isolated network namespace with a stand-in model provider. Skills need no extra step: Muse reads `~/.agents/skills` and `AGENTS.md`. `setup` detects Muse by its config or data directory. No managed workstream (`ai-memory run muse`) and no transcript backfill. See [`install.md`](install.md#meta-muse-code). |
diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.json
index 92addbc5..29a76b2a 100644
--- a/plugins/claude-code/hooks/hooks.json
+++ b/plugins/claude-code/hooks/hooks.json
@@ -45,6 +45,17 @@
]
}
],
+ "PostToolUseFailure": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/scripts/ai-memory-hook\" claude-code post-tool-use"
+ }
+ ]
+ }
+ ],
"PreCompact": [
{
"matcher": "",