Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): install-hooks, session-aware MCP bridge and setup for Meta Muse Code
AkitaOnRailsb05e5371f840
diff --git a/AGENTS.md b/AGENTS.mdindex ad569b3a..c96f2355 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -78,7 +78,7 @@ install or refresh work.If you're about to write a durable project rule ("always X", "neverY", "all PRs must ..."), write it in the project's canonical agent instruction file.Many projects use CLAUDE.md for Claude Code and-AGENTS.md for Codex / OpenCode / OpenCode 2 / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI / Command Code / GitHub Copilot CLI,+AGENTS.md for Codex / OpenCode / OpenCode 2 / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI / Command Code / GitHub Copilot CLI / Muse Code,but if the project says one file is canonical, use that file.Claude Code loads `CLAUDE.md` and does not read `AGENTS.md`. In a project@@ -100,7 +100,7 @@ latest binary's recommended copy:- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting in this project". The agent calls `memory_install_self_routing`,picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /- OpenCode / OpenCode 2 / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI / Command Code / Copilot CLI -> `AGENTS.md`),+ OpenCode / OpenCode 2 / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI / Command Code / Copilot CLI / Muse Code -> `AGENTS.md`),uses its Write / Edit tool to replace or append the returned`markered_block` while preservingnon-ai-memory user content, then writes or updates each returneddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex b40eda8d..02ce1eaf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -383,12 +383,13 @@ and [0.x](docs/changelog/0.x.md).`[auth] bearer_token` is a startup error, and a server whose configured fileis missing or empty refuses to start. A token read from the file is neverwritten into a harness config: `install-mcp` registers Claude Code through- the session-aware `ai-memory mcp-bridge`, gives Codex and Prime Agent a+ the session-aware `ai-memory mcp-bridge` (Muse Code always gets the bridge,+ as `mcp-bridge --agent muse`), gives Codex and Prime Agent areference to `$AI_MEMORY_AUTH_TOKEN`, and writes every other client a stdioentry for `ai-memory mcp-bridge --no-session-id` in that client's own configformat (OpenCode, OpenCode 2, Cursor, Claude Desktop, Gemini CLI, OpenClaw,OMP, Antigravity CLI, Zero, Devin, Grok, Kimi Code, Kiro CLI, Command Code,- Copilot CLI, Swival, VS Code, Zed, Muse Code; DeepSeek Harness's printed+ Copilot CLI, Swival, VS Code, Zed; DeepSeek Harness's printedpatch too). Only ZCode, whose config keeps HTTP entries only, is refused withthe manual option. `uninstall` recognises these entries.`install-hooks --apply` stores the token in the hook credential files only.@@ -438,6 +439,52 @@ and [0.x](docs/changelog/0.x.md).applies to them: verified against the Droid 0.240.0 tool schemas; notool-call id in Droid payloads. `setup-agent --agent droid` prints thehook config and `uninstall` removes both entries. (#1240)+- Added first-class Meta Muse Code support. `install-hooks --agent muse`+ (aliases `muse-code`, `musecode`) merges native+ `ai-memory hook --event … --agent muse` commands for eight events+ (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,+ `PostToolUseFailure`, `PreCompact`, `Stop`, `SessionEnd`) into the `hooks`+ key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, with an empty+ matcher, a 30-second timeout and the server URL and data dir baked in,+ since Muse runs hooks with a cleared environment. It keeps+ `"schema_version": 1`, every other key and your own hooks, writes a backup+ when it changes the file, and changes nothing on a re-run. Sessions are+ recorded as agent `muse` under Muse's own session id (migration V80). The+ `SessionStart` hook delivers the pending handoff through+ `hookSpecificOutput.additionalContext`, the `SessionStart` and+ `UserPromptSubmit` hooks print nothing when there is nothing to deliver+ (Muse adds that stdout to the model's context), and Muse's own `SessionEnd`+ closes the session. Muse's `read_file`, `write_file`, `edit_file`,+ `apply_patch`, `search`, `bash`, `monitor`, `web_fetch` and memory tools map+ to the file, search and shell families, with a relative `path` resolved+ lexically against `cwd`, so `[capture] ignore_paths` and the server drop+ list apply; Muse's `tool_use_id` is kept as the call id. `SubagentStart` and+ `SubagentStop` are not wired, because Muse fires them every turn for its+ built-in reminder observers. `install-mcp --client muse` now writes a stdio+ `ai-memory mcp-bridge --agent muse` entry with `"mode": "optional"` and the+ install's `--data-dir`, replacing the streamable-HTTP entry, so Muse is a+ session-aware client: the new `mcp-bridge --agent muse` forwards+ `MUSE_SESSION_ID` and reads no other harness's variable (`--agent+ claude-code`, the default, reads only `CLAUDE_CODE_SESSION_ID`). The entry+ goes under `mcpServers`, or under the legacy `mcp_servers` when the file+ already uses it, never both; a file holding both maps, which makes Muse+ ignore every MCP server, is refused and reported by `doctor`. The settings+ path follows `XDG_CONFIG_HOME`. The Claude Code plugin launcher records an+ event as `muse` when Muse runs it (`MUSE_PLUGIN_ID` with `MUSE_SESSION_ID`),+ skipping the events the Muse settings hooks deliver, its subagent events and+ folderless sessions. `setup` detects Muse by its config or data directory,+ `setup-agent --agent muse` prints the hook config, `doctor` reports the Muse+ wiring, `uninstall` removes the hooks and the entry from either map, the+ Docker wrapper forwards `MUSE_SESSION_ID`, and the routing snippet lists+ Muse Code among the `AGENTS.md` harnesses. Verified offline against Muse+ Code 1.4.7 hook payloads, and end to end with the real Muse binary in an+ isolated network namespace against a stand-in model provider: capture of+ all eight events, exclusions on relative and absolute paths, MCP calls+ routed by session, handoff injection and the timeout unit. Not verified:+ interactive `SessionStart` sources and `SessionEnd` reasons, `PreCompact`+ payloads, `apply_patch` and `monitor` input shapes, macOS and Windows paths,+ and the plugin from the marketplace, which Muse Code 1.4.7 refuses to+ install because its `.mcp.json` uses `${user_config.*}` placeholders.- Added an optional TypeScript client SDK in `companions/ai-memory-ts` forprograms that are not coding-agent harnesses: custom agents, bots, editorand app extensions, scripts and CI jobs. `AiMemoryClient` wraps the page,diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex aacf374a..ac8a1a5e 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -22,7 +22,8 @@ Linux or macOS it takes two commands, and neither needs root.`<self>` is one of `claude-code`, `codex`, `opencode`, `opencode2`,`gemini-cli`, `cursor`, `kimi-code`, `kiro-cli`, `grok`, `copilot-cli`,- `antigravity-cli`, `command-code`, `devin`, `droid`, `omp`, `pi`, `openclaw`+ `antigravity-cli`, `command-code`, `devin`, `droid`, `muse`, `omp`, `pi`,+ `openclaw`(`ai-memory setup --help` lists every value). Repeat `--agent` to wireseveral harnesses. Without `--agent`, `setup` wires every harness it findsunder the home directory.diff --git a/README.md b/README.mdindex e926592c..65c4a6f4 100644--- a/README.md+++ b/README.md@@ -143,9 +143,9 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).| Pool | Hooks-only || GitHub Copilot CLI | Supported || Factory Droid | Supported |+| Meta Muse Code | Supported || VS Code Copilot | MCP-only || Zed | MCP-only |-| Muse Code | MCP-only || DeepSeek Harness (DSH) | MCP-only || Prime Agent | MCP-only || Hermes Agent | Supported |@@ -358,7 +358,7 @@ docker run -d --name ai-memory \# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts and each client's config-path detection. Re-run with# `--agent codex`, `--agent command-code`, `--agent devin`, `--agent opencode`, `--agent opencode2`, `--agent gemini-cli`,-# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--agent omp`,+# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--agent muse`, `--agent omp`,# `--agent oh-my-pi`, `--client cursor`,# `--client gemini-cli`, `--client grok`, `--client kiro-cli`, etc.# for additional agents; full list in docs/install.md.diff --git a/bin/ai-memory b/bin/ai-memoryindex ac5a3de6..811fe250 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -733,6 +733,7 @@ for var in \AI_MEMORY_HOOKS_HOST_ROOT \CLAUDE_CONFIG_DIR \CLAUDE_CODE_SESSION_ID \+ MUSE_SESSION_ID \ANTHROPIC_API_KEY \ANTHROPIC_OAUTH_TOKEN \CLAUDE_CODE_OAUTH_TOKEN \diff --git a/bin/ai-memory.ps1 b/bin/ai-memory.ps1index 09c9ff9f..5a22b1d2 100644--- a/bin/ai-memory.ps1+++ b/bin/ai-memory.ps1@@ -154,6 +154,7 @@ foreach ($Name in @("AI_MEMORY_WORKSTREAM_ID","CLAUDE_CONFIG_DIR","CLAUDE_CODE_SESSION_ID",+ "MUSE_SESSION_ID","ANTHROPIC_API_KEY","ANTHROPIC_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN",diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 9994593e..2834f73a 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -2422,6 +2422,16 @@ pub enum AgentChoice {/// Droid's own `SessionEnd` closes the session.#[value(alias = "factory-droid")]Droid,+ /// Meta Muse Code (`muse`) — lifecycle hooks merged into the `hooks` key+ /// of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, keeping its+ /// `schema_version` and every other key. Muse sends Claude Code-shaped+ /// hook payloads on stdin with a cleared environment, so each entry runs+ /// ai-memory's native `hook` command with the server, data dir and agent+ /// baked in; there is no script bundle. SessionStart stdout+ /// (`hookSpecificOutput.additionalContext`) carries the handoff, and+ /// Muse's own `SessionEnd` closes the session.+ #[value(alias = "muse-code", alias = "musecode")]+ Muse,}impl AgentChoice {@@ -2454,6 +2464,7 @@ impl AgentChoice {Self::Hermes => AgentKind::Hermes,Self::CopilotCli => AgentKind::CopilotCli,Self::Droid => AgentKind::Droid,+ Self::Muse => AgentKind::Muse,}}@@ -2473,7 +2484,8 @@ impl AgentChoice {| Self::Zero| Self::Zcode| Self::Hermes- | Self::Droid => None,+ | Self::Droid+ | Self::Muse => None,_ => Some(self.kind().as_str()),}}@@ -2703,21 +2715,23 @@ pub enum McpClient {/// `context_servers` map. This integration is MCP-only because Zed/// does not expose ai-memory-compatible lifecycle hooks.Zed,- /// Muse Code (Meta) — `~/.config/muse/settings.json`, servers under a- /// top-level snake_case `mcp_servers` map with `transport:- /// "streamable_http"` + `url` + `headers`.+ /// Meta Muse Code — `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`.+ /// The entry is a stdio `ai-memory mcp-bridge --agent muse`, which+ /// forwards the `MUSE_SESSION_ID` Muse gives its stdio servers, so Muse+ /// is a session-aware client (a streamable-HTTP entry carries no session+ /// id).///- /// Two documented constraints shape the generated entry. The settings- /// file must carry `"schema_version": 1` or *every* Muse Code command- /// fails at startup with `malformed settings file`, so the writer adds- /// the key when it is absent and never rewrites an existing value. And- /// `mode` defaults to `required`, which aborts the whole Muse run when- /// the server is unreachable; ai-memory augments a session rather than- /// gating it, so the entry sets `mode: "optional"` explicitly.- ///- /// MCP-only: Muse Code's hook surface is documented but its- /// `SessionStart` output contract is not, so lifecycle capture and- /// managed workstreams are not claimed. See `install-mcp --client muse`.+ /// Muse reads servers from `mcpServers` (`type: "stdio"`) or the legacy+ /// `mcp_servers` (`transport: "stdio"`), and drops the whole MCP block+ /// when both are present. The writer uses `mcp_servers` when the file+ /// already has it, else `mcpServers`, never adds the second, and refuses+ /// a file that already holds both. The settings file must carry+ /// `"schema_version": 1` or every Muse command fails at startup, so the+ /// writer adds the key when it is absent and never rewrites an existing+ /// value. `mode` defaults to `required`, which aborts the whole Muse run+ /// when the server cannot start, so the entry sets `mode: "optional"`.+ /// Pair with `install-hooks --agent muse` for lifecycle capture.+ #[value(alias = "muse-code", alias = "musecode")]Muse,/// DeepSeek Harness (DSH) - MCP-only. DSH has no fixed JSON/TOML MCP/// config: the client is a Cordis plugin entry@@ -3259,6 +3273,12 @@ pub struct InstallMcpArgs {/// in `[auth].bearer_token_file`.#[arg(skip)]pub stdio_bridge: bool,+ /// The data dir a bridge entry passes as `--data-dir`, for a client that+ /// starts its MCP servers with a cleared environment (Muse Code), where+ /// the bridge could not otherwise find this install's config and token.+ /// Set by the installer, never a flag.+ #[arg(skip)]+ pub bridge_data_dir: Option<std::path::PathBuf>,}/// Arguments for the internal stdio-to-HTTP MCP bridge.@@ -3268,10 +3288,40 @@ pub struct McpBridgeArgs {#[arg(long)]pub server_url: Option<String>,/// Run as a plain stdio-to-HTTP bridge that forwards no session identity,- /// for MCP clients other than Claude Code. Without it the bridge forwards- /// `CLAUDE_CODE_SESSION_ID` and refuses to start when it is missing.+ /// for MCP clients other than Claude Code and Muse Code. Without it the+ /// bridge forwards the session id of the `--agent` that launched it and+ /// refuses to start when it is missing.#[arg(long)]pub no_session_id: bool,+ /// The harness that launches this session-aware bridge, which names the+ /// one variable its session id is read from: `claude-code` (the default)+ /// reads `CLAUDE_CODE_SESSION_ID`, `muse` reads `MUSE_SESSION_ID`. The+ /// other variable is never consulted, so an id inherited from a+ /// different harness's terminal is not forwarded.+ #[arg(long, value_enum, default_value_t = BridgeAgent::ClaudeCode)]+ pub agent: BridgeAgent,+}++/// The harness a session-aware `mcp-bridge` forwards the session id of.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]+pub enum BridgeAgent {+ /// Claude Code: `CLAUDE_CODE_SESSION_ID`.+ #[default]+ ClaudeCode,+ /// Meta Muse Code: `MUSE_SESSION_ID`.+ #[value(alias = "muse-code", alias = "musecode")]+ Muse,+}++impl BridgeAgent {+ /// The variable this harness puts its session id in.+ #[must_use]+ pub const fn session_env(self) -> &'static str {+ match self {+ Self::ClaudeCode => "CLAUDE_CODE_SESSION_ID",+ Self::Muse => "MUSE_SESSION_ID",+ }+ }}/// Transport for the MCP server.@@ -4524,6 +4574,42 @@ mod tests {}}+ #[test]+ fn muse_install_hooks_install_mcp_and_mcp_bridge_parse_with_their_aliases() {+ for alias in ["muse", "muse-code", "musecode"] {+ let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])+ .unwrap_or_else(|error| panic!("{alias}: {error}"));+ let Command::InstallHooks(args) = hooks.command else {+ panic!("expected install-hooks");+ };+ assert_eq!(args.agent, AgentChoice::Muse);+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Muse);+ // Native commands only: there is no `hooks/muse` bundle.+ assert_eq!(args.agent.script_hook_subdir(), None);++ let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])+ .unwrap_or_else(|error| panic!("{alias}: {error}"));+ let Command::InstallMcp(args) = mcp.command else {+ panic!("expected install-mcp");+ };+ assert_eq!(args.client, McpClient::Muse);++ let bridge = Cli::try_parse_from(["ai-memory", "mcp-bridge", "--agent", alias])+ .unwrap_or_else(|error| panic!("{alias}: {error}"));+ let Command::McpBridge(args) = bridge.command else {+ panic!("expected mcp-bridge");+ };+ assert_eq!(args.agent, BridgeAgent::Muse);+ assert_eq!(args.agent.session_env(), "MUSE_SESSION_ID");+ }+ let bridge = Cli::try_parse_from(["ai-memory", "mcp-bridge"]).unwrap();+ let Command::McpBridge(args) = bridge.command else {+ panic!("expected mcp-bridge");+ };+ assert_eq!(args.agent, BridgeAgent::ClaudeCode);+ assert_eq!(args.agent.session_env(), "CLAUDE_CODE_SESSION_ID");+ }+#[test]fn copilot_cli_install_hooks_agent_parses_without_a_bare_copilot_alias() {let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "copilot-cli"])diff --git a/crates/ai-memory-cli/src/commands/auth_enable.rs b/crates/ai-memory-cli/src/commands/auth_enable.rsindex 52a78eea..ee9b996e 100644--- a/crates/ai-memory-cli/src/commands/auth_enable.rs+++ b/crates/ai-memory-cli/src/commands/auth_enable.rs@@ -283,6 +283,7 @@ fn rewire(flavor,token_env_var: false,stdio_bridge: false,+ bridge_data_dir: None,};// Name the OpenCode major version outright: both share one file, and// probing `opencode --version` here would pick one for both locations.diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex 13fc1435..4fadd4d2 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -192,6 +192,9 @@ struct DoctorReport {/// The ai-memory marketplace plugins installed for Claude Code and Codex,/// with version skew and any parallel settings-file wiring (#1166).plugins: Vec<PluginReport>,+ /// Meta Muse Code's settings file, when there is one: whether ai-memory's+ /// hooks and MCP entry are in it, and the two shapes that break Muse.+ muse: Option<MuseReport>,}/// One installed ai-memory marketplace plugin and what else wires the same@@ -645,6 +648,10 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {}).await;+ let muse = super::install_hooks::muse_settings_path(&config.runtime_env)+ .ok()+ .and_then(|path| muse_report(&path));+let auth_posture = identity.as_ref().map(|identity| {crate::local_auth::AuthPosture::classify(identity.level == "anonymous", &ep.url)});@@ -667,6 +674,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {codex_hooks,agentmemory_residue,plugins,+ muse,};if args.json {@@ -697,6 +705,76 @@ async fn codex_hook_trust(.await}+/// What `doctor` reads from Meta Muse Code's `settings.json`.+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+struct MuseReport {+ settings: String,+ /// The `hooks` key carries `install-hooks --agent muse` entries.+ hooks_wired: bool,+ /// The server map holding an `ai-memory` entry, if any.+ mcp_entry: Option<&'static str>,+ /// Both `mcpServers` and `mcp_servers` are present: Muse then ignores+ /// every MCP server.+ conflicting_server_maps: bool,+ /// No `schema_version`: every muse command fails at startup.+ schema_version_missing: bool,+}++/// [`MuseReport`] for the settings file at `path`; `None` when it does not+/// exist or is not a JSON object.+fn muse_report(path: &Path) -> Option<MuseReport> {+ let text = std::fs::read_to_string(path).ok()?;+ let root: serde_json::Value = serde_json::from_str(&text).ok()?;+ let root = root.as_object()?;+ let mcp_entry = ["mcpServers", "mcp_servers"].into_iter().find(|key| {+ root.get(*key)+ .and_then(|servers| servers.get("ai-memory"))+ .is_some()+ });+ Some(MuseReport {+ settings: path.display().to_string(),+ hooks_wired: super::install_hooks::settings_file_carries_ai_memory_hooks(path),+ mcp_entry,+ conflicting_server_maps: root.contains_key("mcpServers")+ && root.contains_key("mcp_servers"),+ schema_version_missing: !root.contains_key("schema_version"),+ })+}++/// Human lines for Muse's settings file; empty without one.+fn render_muse(report: Option<&MuseReport>) -> String {+ let Some(report) = report else {+ return String::new();+ };+ let mut out = format!(+ " muse: {} (hooks {}, MCP entry {})\n",+ report.settings,+ if report.hooks_wired {+ "wired"+ } else {+ "not wired: run `ai-memory install-hooks --agent muse --apply`"+ },+ report+ .mcp_entry+ .map_or_else(|| "absent".to_owned(), |key| format!("under `{key}`")),+ );+ if report.conflicting_server_maps {+ out.push_str(&format!(+ "⚠ {} has both `mcpServers` and `mcp_servers`, so Muse ignores every MCP server. \+ Move the servers into one of the two maps.\n",+ report.settings+ ));+ }+ if report.schema_version_missing {+ out.push_str(&format!(+ "⚠ {} has no \"schema_version\", so every muse command fails at startup. Add \+ \"schema_version\": 1.\n",+ report.settings+ ));+ }+ out+}+/// The installed ai-memory plugins, each with what else wires its harness./// Asking Codex for hook trust starts it, so that runs only when the Codex/// plugin is enabled.@@ -1030,6 +1108,7 @@ fn render_human(report: &DoctorReport) {}print!("{}", render_capture_health(report));print!("{}", render_plugins(&report.plugins));+ print!("{}", render_muse(report.muse.as_ref()));print!("{}",super::agentmemory_residue::render(&report.agentmemory_residue)@@ -1161,9 +1240,45 @@ mod tests {codex_hooks,agentmemory_residue: Vec::new(),plugins: Vec::new(),+ muse: None,}}+ /// Doctor reads Muse's settings file: the wiring it finds, and the two+ /// shapes that break Muse (both server maps, no `schema_version`).+ #[test]+ fn doctor_reports_muse_wiring_and_breaking_shapes() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("settings.json");+ assert_eq!(muse_report(&path), None);+ assert_eq!(render_muse(None), "");++ std::fs::write(+ &path,+ r#"{"schema_version":1,"mcp_servers":{"ai-memory":{"transport":"stdio"}},"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/ai-memory hook --event stop --agent muse --server-url http://127.0.0.1:49374"}]}]}}"#,+ )+ .unwrap();+ let wired = muse_report(&path).unwrap();+ assert!(wired.hooks_wired);+ assert_eq!(wired.mcp_entry, Some("mcp_servers"));+ assert!(!wired.conflicting_server_maps);+ assert!(!wired.schema_version_missing);+ let text = render_muse(Some(&wired));+ assert!(text.contains("hooks wired"), "{text}");+ assert!(!text.contains('⚠'), "{text}");++ std::fs::write(&path, r#"{"mcpServers":{},"mcp_servers":{}}"#).unwrap();+ let broken = muse_report(&path).unwrap();+ assert!(!broken.hooks_wired);+ assert_eq!(broken.mcp_entry, None);+ assert!(broken.conflicting_server_maps);+ assert!(broken.schema_version_missing);+ let text = render_muse(Some(&broken));+ assert!(text.contains("ignores every MCP server"), "{text}");+ assert!(text.contains("schema_version"), "{text}");+ assert!(text.contains("not wired"), "{text}");+ }+/// Doctor reports the plugin and every way the same harness is wired/// twice: settings hooks, installed skills, a second MCP entry, a setting/// that disables plugin hooks, and version skew. A plugin alone is quiet.diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex c1215a54..434b3499 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -541,6 +541,13 @@ fn write_success_response<W: std::io::Write>(// context, and v2/v3 Stop parse stdout for a block decision. Capture-only// hooks therefore stay silent unless SessionStart has real context.Ok(())+ } else if agent == AgentKind::Muse+ && matches!(event, HookEvent::SessionStart | HookEvent::UserPrompt)+ {+ // Muse adds SessionStart and UserPromptSubmit stdout to the turn as+ // developer context, so a capture-only reply stays empty rather than+ // put `{}` in front of the model on every prompt.+ Ok(())} else if event == HookEvent::UserPrompt && agent.user_prompt_injects_handoff() {// Kimi Code injects any non-empty UserPromptSubmit stdout into the turn// verbatim, so a `{}` here would become user-visible text on every@@ -5752,6 +5759,100 @@ mod tests {);}+ /// Muse injects SessionStart's `hookSpecificOutput.additionalContext` as+ /// developer context (verified offline on Muse Code 1.4.7), so `--agent+ /// muse` fetches the handoff for the payload's UUIDv7 session id and+ /// prints Claude Code's envelope.+ #[tokio::test]+ async fn muse_session_start_prints_hook_specific_handoff_envelope() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "MUSE-HANDOFF").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(tmp.path().join("data")),+ HookArgs {+ agent: "muse".into(),+ ..copilot_cli_hook_args("session-start", &base)+ },+ serde_json::json!({+ "cwd": tmp.path(),+ "hook_event_name": "SessionStart",+ "model": "muse-wonder-1.0",+ "model_provider": "meta",+ "permission_mode": "bypassPermissions",+ "session_id": "01a13669-dc61-7a72-b5ec-ad2f300ffd26",+ "source": "startup",+ "transcript_path": null+ })+ .to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ let envelope: serde_json::Value = serde_json::from_slice(stdout.trim_ascii()).unwrap();+ assert_eq!(+ envelope,+ serde_json::json!({+ "hookSpecificOutput": {+ "hookEventName": "SessionStart",+ "additionalContext": "MUSE-HANDOFF",+ }+ })+ );+ let mut recorded = Vec::new();+ while let Some(request) = first_request(&mut requests).await {+ recorded.push(request);+ }+ assert!(+ recorded.iter().any(|request| {+ request.starts_with("GET /handoff?")+ && request.contains("agent=muse")+ && request.contains("session_id=01a13669-dc61-7a72-b5ec-ad2f300ffd26")+ }),+ "{recorded:?}"+ );+ }++ /// Muse adds SessionStart and UserPromptSubmit stdout to the turn as+ /// developer context, so with no handoff to deliver the hook prints+ /// nothing there, never `{}`. Control: its Stop still replies `{}`, and+ /// Droid's prompt hook still prints `{}`.+ #[tokio::test]+ async fn muse_context_events_print_nothing_without_a_handoff() {+ let run = |agent: &'static str, event: &'static str| async move {+ let tmp = tempfile::tempdir().unwrap();+ let (base, _requests) = serve_requests("404 Not Found", "").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(tmp.path().join("data")),+ HookArgs {+ agent: agent.into(),+ ..copilot_cli_hook_args(event, &base)+ },+ serde_json::json!({+ "cwd": tmp.path(),+ "hook_event_name": "UserPromptSubmit",+ "prompt": "Please do the file steps.",+ "session_id": "01a13669-dc61-7a72-b5ec-ad2f300ffd26",+ "transcript_path": null,+ "turn_id": "ccfe4a87-c654-49f5-b5e9-473015c7a90b"+ })+ .to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();+ String::from_utf8(stdout).unwrap()+ };+ assert_eq!(run("muse", "user-prompt-submit").await, "");+ assert_eq!(run("muse", "session-start").await, "");+ assert_eq!(run("muse", "stop").await.trim(), "{}");+ assert_eq!(run("droid", "user-prompt-submit").await.trim(), "{}");+ }+// ── #992: per-repository server profiles ─────────────────────────────/// Register `name` in `data_dir` with a token and the given roots.@@ -5952,6 +6053,118 @@ mod tests {assert_eq!(entries[1].profile.as_deref(), Some("team-b"));}+ /// Front door for Meta Muse Code's settings.json hooks (adversarial),+ /// with Muse Code 1.4.7 payload shapes: a prompt from a marked checkout+ /// is scoped by its marker, routed to the marker's server profile with+ /// the profile's token (never the install's), and keyed by the payload's+ /// UUIDv7 session id; a `read_file` of an ignored relative path from that+ /// checkout is dropped before the spool while a control path is kept;+ /// allowlist mode emits nothing from an unmarked checkout (printing+ /// nothing either), and the same prompt without allowlist is captured.+ #[tokio::test]+ async fn muse_hooks_honour_marker_scope_profiles_exclusions_and_allowlist() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let repo = repo_with_marker(+ tmp.path(),+ "repo",+ "workspace = \"mw\"\nproject = \"mp\"\nserver = \"team-a\"\n[capture]\nignore_paths = [\"secret/**\"]\n",+ );+ register_profile(+ &data_dir,+ "team-a",+ "https://a.example",+ &[&repo],+ Some("tok-a"),+ );+ crate::config::store_hook_auth_token(&data_dir, "INSTALL-TOKEN").unwrap();+ let session = "01a13669-dc61-7a72-b5ec-ad2f300ffd26";+ let muse = |event: &str| {+ let mut args = claude_args(event, "https://default.example");+ args.agent = "muse".into();+ args+ };+ let run = |args: HookArgs, payload: serde_json::Value| {+ let data_dir = data_dir.clone();+ async move {+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir),+ args,+ payload.to_string(),+ &mut stdout,+ |_, _| panic!("a Muse event must only spool"),+ )+ .await+ .unwrap();+ stdout+ }+ };+ let prompt = |cwd: &Path| {+ serde_json::json!({+ "cwd": cwd,+ "hook_event_name": "UserPromptSubmit",+ "model": "muse-wonder-1.0",+ "model_provider": "meta",+ "permission_mode": "bypassPermissions",+ "prompt": "Please do the file steps.",+ "session_id": session,+ "transcript_path": null,+ "turn_id": "ccfe4a87-c654-49f5-b5e9-473015c7a90b"+ })+ };+ let read = |path: &str| {+ serde_json::json!({+ "cwd": repo,+ "hook_event_name": "PostToolUse",+ "session_id": session,+ "tool_input": {"path": path},+ "tool_name": "read_file",+ "tool_response": format!("Read text file `{path}`.\n1|SECRET-BODY"),+ "tool_use_id": "call_bc48188330cd",+ "transcript_path": null+ })+ };++ run(muse("user-prompt-submit"), prompt(&repo)).await;+ let spool = hook_spool::spool_dir(&data_dir);+ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 1);+ let url = &entries[0].url;+ assert!(url.starts_with("https://a.example/hook?"), "{url}");+ assert_eq!(entries[0].token.as_deref(), Some("tok-a"));+ assert_eq!(query_param(url, "agent"), Some("muse"));+ assert_eq!(query_param(url, "workspace"), Some("mw"));+ assert_eq!(query_param(url, "project"), Some("mp"));+ let body: serde_json::Value = serde_json::from_str(&entries[0].body).unwrap();+ assert_eq!(body["session_id"], session);++ run(muse("post-tool-use"), read("secret/a.txt")).await;+ assert_eq!(+ read_spooled_entries(&spool).len(),+ 1,+ "an ignored relative path is dropped before the spool"+ );+ run(muse("post-tool-use"), read("src/lib.rs")).await;+ assert_eq!(read_spooled_entries(&spool).len(), 2, "control path kept");++ let unmarked = tmp.path().join("unmarked");+ std::fs::create_dir_all(&unmarked).unwrap();+ let mut allowlist = muse("user-prompt-submit");+ allowlist.capture_mode = Some(crate::cli::CaptureModeArg::Allowlist);+ let stdout = run(allowlist, prompt(&unmarked)).await;+ assert!(stdout.is_empty(), "{:?}", String::from_utf8_lossy(&stdout));+ assert_eq!(read_spooled_entries(&spool).len(), 2, "allowlist drop");+ run(muse("user-prompt-submit"), prompt(&unmarked)).await;+ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 3, "control: denylist captures it");+ assert!(+ entries[2].url.starts_with("https://default.example/hook?"),+ "{}",+ entries[2].url+ );+ }+/// Backward compatibility: without a `server` key the install default is/// used exactly as before, and the spooled entry carries no profile.#[tokio::test]diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex ff811d26..a940b6b7 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -430,6 +430,15 @@ pub(crate) fn droid_hooks_path() -> anyhow::Result<std::path::PathBuf> {.join("hooks.json"))}+/// `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json` — Meta Muse Code's user+/// settings, whose `hooks` key holds its lifecycle hooks. `XDG_CONFIG_HOME`+/// comes from the captured environment (invariant #1).+pub(crate) fn muse_settings_path(+ env: &crate::config::RuntimeEnv,+) -> anyhow::Result<std::path::PathBuf> {+ install_mcp::muse_settings_path_in(env.var_os("XDG_CONFIG_HOME"), home_dir())+}+/// `~/.config/zero/hooks.json` — Zero's user-level lifecycle hook config/// (issue #156). Zero resolves it under `$XDG_CONFIG_HOME` falling back to/// `~/.config`; like the OpenCode plugin path below we target the default@@ -793,6 +802,10 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(if args.apply && args.agent == AgentChoice::Codex && args.config_file.is_none() {args.config_file = Some(codex_hooks_path(&config.runtime_env)?);}+ // Muse's settings file follows XDG_CONFIG_HOME, resolved the same way.+ if args.apply && args.agent == AgentChoice::Muse && args.config_file.is_none() {+ args.config_file = Some(muse_settings_path(&config.runtime_env)?);+ }// Preserve an existing `--capture-assistant` opt-in on a bare re-apply. There// is no negative flag, so a re-run without `--capture-assistant` (notably the// `ai-memory run` auto-wire, which always passes it off) must NOT silently@@ -962,6 +975,13 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(};apply_to_droid_hooks(&path, &server_url, auth, &config.data_dir, &args)}+ AgentChoice::Muse => {+ let path = args+ .config_file+ .clone()+ .context("internal: the Muse settings path is resolved before apply")?;+ apply_to_muse_settings(&path, &server_url, auth, &config.data_dir, &args)+ }};}let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);@@ -1117,6 +1137,7 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path()}AgentChoice::Droid => render_droid(&server_url, auth, &config.data_dir, strategy),+ AgentChoice::Muse => render_muse(&server_url, auth, &config.data_dir, strategy),}}@@ -1309,6 +1330,8 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {AgentChoice::KiroCliV3 => kiro_cli_v3_hooks_path().ok()?,AgentChoice::CopilotCli => copilot_cli_hooks_path().ok()?,AgentChoice::Droid => droid_hooks_path().ok()?,+ // `run` resolves it into `args.config_file` before any caller.+ AgentChoice::Muse => return None,}};std::fs::read_to_string(path).ok()@@ -1656,14 +1679,7 @@ fn infer_installed_mcp_config(&["context_servers", "ai-memory"],"url",)),- // MCP-only client: no AgentChoice counterpart routes here. Muse- // Code's hook surface is documented, but its SessionStart output- // contract is not, so no lifecycle integration claims it yet.- McpClient::Muse => Ok(infer_json_mcp_config(- &content,- &["mcp_servers", "ai-memory"],- "url",- )),+ McpClient::Muse => Ok(infer_muse_mcp_config(&content)),// MCP-only client: no AgentChoice counterpart routes here. Prime// Agent 0.10 has no lifecycle hooks, and its entry names the token// variable rather than carrying a bearer, so only the URL is there.@@ -1738,6 +1754,7 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::Hermes => None,AgentChoice::CopilotCli => Some(McpClient::CopilotCli),AgentChoice::Droid => Some(McpClient::Droid),+ AgentChoice::Muse => Some(McpClient::Muse),}}@@ -1821,6 +1838,41 @@ fn infer_json_mcp_config(})}+/// Infer the hook server URL and bearer from Muse's `ai-memory` entry, under+/// `mcpServers` or the legacy `mcp_servers`. The entry `install-mcp --client+/// muse` writes is the stdio bridge, whose upstream is its `--server-url`+/// argument and whose token, when one was given explicitly, is the literal+/// `env.AI_MEMORY_AUTH_TOKEN`; an older streamable-HTTP entry carries `url`+/// and an `Authorization` header instead. A `${...}` reference is never taken+/// for a token.+fn infer_muse_mcp_config(content: &str) -> Option<InferredMcpConfig> {+ let root: serde_json::Value = serde_json::from_str(content).ok()?;+ let entry = ["mcpServers", "mcp_servers"]+ .iter()+ .find_map(|key| root.get(*key)?.get("ai-memory"))?;+ let hook_server_url = entry+ .get("url")+ .and_then(serde_json::Value::as_str)+ .or_else(|| install_mcp::bridge_entry_url(entry))+ .and_then(hook_server_url_from_mcp_url);+ let auth_token = entry+ .get("headers")+ .and_then(|headers| headers.get("Authorization"))+ .and_then(serde_json::Value::as_str)+ .and_then(bearer_token_from_header)+ .or_else(|| {+ entry+ .pointer("/env/AI_MEMORY_AUTH_TOKEN")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned)+ })+ .filter(|token| !token.trim().is_empty() && !token.contains("${"));+ Some(InferredMcpConfig {+ hook_server_url,+ auth_token,+ })+}+/// Infer hook server URL + bearer from a TOML `[mcp_servers.ai-memory]`/// entry (Codex `http_headers` or Grok `headers`).fn infer_toml_mcp_config(content: &str) -> Option<InferredMcpConfig> {@@ -7009,6 +7061,102 @@ fn render_droid(Ok(())}+/// Merge ai-memory's entries into the `hooks` key of Muse's `settings.json`,+/// keeping `schema_version`, every unknown key and every other hook in it,+/// idempotently, with a backup next to the file on change. Muse fails every+/// command at startup when the file has no `schema_version`, so a new file+/// gets `"schema_version": 1`; an existing value is never rewritten.+fn apply_to_muse_settings(+ path: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);+ let payload = super::render_shared::build_muse_hooks_payload(+ server_url,+ auth_token,+ Some(data_dir),+ strategy,+ );+ let our_hooks = payload+ .get("hooks")+ .and_then(serde_json::Value::as_object)+ .context("internal: build_muse_hooks_payload didn't return a hooks object")?;+ let outcome = apply_atomic(path, |existing| {+ mutate_json(existing, |root| {+ root.entry("schema_version")+ .or_insert_with(|| serde_json::Value::from(1));+ let hooks = root+ .entry("hooks")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`hooks` is present in the Muse settings.json but not an object")?;+ for (event, value) in our_hooks {+ overlay_event_hooks(hooks, event, value);+ }+ Ok(())+ })+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ print!("{MUSE_INSTALL_NOTES}");+ Ok(())+}++const MUSE_INSTALL_NOTES: &str = "\+# NOTE: Muse adds SessionStart's additionalContext to the session, so the+# prior session's handoff is delivered automatically, and its own+# SessionEnd closes the session.+# NOTE: Muse runs hooks with a cleared environment, so the server URL and+# data dir are baked into each command; re-run this command after+# changing either. Start a new muse session to load the new hooks.+";++/// Print the `hooks` block for Muse's `settings.json` (dry-run counterpart of+/// [`apply_to_muse_settings`]).+fn render_muse(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ let payload = super::render_shared::build_muse_hooks_payload(+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let mut snippet = serde_json::Map::new();+ snippet.insert("schema_version".into(), serde_json::Value::from(1));+ snippet.insert("hooks".into(), payload["hooks"].clone());+ let serialized = serde_json::to_string_pretty(&serde_json::Value::Object(snippet))+ .context("serializing Muse hook config")?;+ println!("# Meta Muse Code hook config — merge the `hooks` entries into");+ println!("# ${{XDG_CONFIG_HOME:-~/.config}}/muse/settings.json, or re-run with --apply");+ println!("# to merge them in place. Keep \"schema_version\": 1: without it every");+ println!("# muse command fails at startup.");+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: this printed snippet embeds the token in each hook command —");+ println!("# treat the file as sensitive (chmod 600). `--apply` stores it");+ println!("# under the data dir instead.");+ }+ print!("{MUSE_INSTALL_NOTES}");+ println!();+ println!("{serialized}");+ Ok(())+}+fn render_devin(hooks_dir: &Path,server_url: &str,@@ -7964,6 +8112,227 @@ mod tests {assert_eq!(pre[0]["hooks"][0]["command"], "/usr/local/bin/guard.sh");}+ fn muse_args(config_file: &Path) -> InstallHooksArgs {+ InstallHooksArgs {+ agent: AgentChoice::Muse,+ config_file: Some(config_file.to_path_buf()),+ ..default_hook_args()+ }+ }++ /// `install-hooks --agent muse --apply` merges native `--agent muse`+ /// commands under the `hooks` key of Muse's `settings.json`: one+ /// catch-all (`matcher: ""`) group per event with a timeout in seconds,+ /// `schema_version` and every unknown key kept, third-party hooks kept,+ /// and a re-apply changes nothing.+ #[test]+ fn muse_apply_merges_native_hooks_into_settings_and_is_idempotent() {+ let muse = TempDir::new().unwrap();+ let data = TempDir::new().unwrap();+ let settings = muse.path().join("settings.json");+ fs::write(+ &settings,+ serde_json::json!({+ "schema_version": 1,+ "theme": "dark",+ "mcpServers": {"x": {"type": "stdio", "command": "x", "mode": "optional"}},+ "hooks": {+ "PreToolUse": [{+ "matcher": "bash",+ "hooks": [{"type": "command", "command": "/usr/local/bin/guard.sh", "timeout": 5}]+ }],+ "Notification": [{"hooks": [{"type": "command", "command": "notify-send hi"}]}]+ }+ })+ .to_string(),+ )+ .unwrap();+ let args = muse_args(&settings);++ apply_to_muse_settings(&settings, "http://memory:49374", None, data.path(), &args).unwrap();+ let first = fs::read_to_string(&settings).unwrap();+ apply_to_muse_settings(&settings, "http://memory:49374", None, data.path(), &args).unwrap();+ assert_eq!(+ first,+ fs::read_to_string(&settings).unwrap(),+ "re-apply is a no-op"+ );+ let backups = fs::read_dir(muse.path())+ .unwrap()+ .filter(|entry| {+ entry+ .as_ref()+ .unwrap()+ .file_name()+ .to_string_lossy()+ .contains(".bak-")+ })+ .count();+ assert_eq!(backups, 1, "only the first apply changed the file");++ let root: serde_json::Value = serde_json::from_str(&first).unwrap();+ assert_eq!(root["schema_version"], 1);+ assert_eq!(root["theme"], "dark");+ assert_eq!(root["mcpServers"]["x"]["command"], "x");+ let hooks = &root["hooks"];+ for (event, script) in super::super::render_shared::MUSE_EVENTS {+ let entries = hooks[event].as_array().unwrap();+ let ours: Vec<_> = entries+ .iter()+ .filter(|e| is_ai_memory_hook_entry(e))+ .collect();+ assert_eq!(ours.len(), 1, "{event}: exactly one ai-memory entry");+ assert_eq!(ours[0]["matcher"], "", "{event}");+ let handler = &ours[0]["hooks"][0];+ assert_eq!(handler["type"], "command", "{event}");+ assert_eq!(+ handler["timeout"],+ super::super::render_shared::MUSE_HOOK_TIMEOUT_SECS,+ "{event}"+ );+ let command = handler["command"].as_str().unwrap();+ let stem = script.trim_end_matches(".sh");+ assert!(+ command.contains(&format!(" hook --event {stem} --agent muse --server-url ")),+ "{event}: {command}"+ );+ assert!(+ command.contains("--data-dir"),+ "{event}: Muse clears the hook environment, so the data dir is baked in: {command}"+ );+ assert!(+ !command.contains(".sh"),+ "{event}: no script bundle: {command}"+ );+ }+ assert!(hooks.get("SubagentStart").is_none());+ assert!(hooks.get("SubagentStop").is_none());+ assert_eq!(+ hooks["Notification"][0]["hooks"][0]["command"],+ "notify-send hi"+ );+ let pre = hooks["PreToolUse"].as_array().unwrap();+ assert_eq!(pre.len(), 2);+ assert_eq!(pre[0]["matcher"], "bash");+ assert_eq!(pre[0]["hooks"][0]["command"], "/usr/local/bin/guard.sh");+ }++ /// A new settings file gets `"schema_version": 1` (without it every+ /// muse command fails at startup); an existing value is never rewritten;+ /// a non-object `hooks` is refused.+ #[test]+ fn muse_apply_creates_schema_version_and_never_rewrites_it() {+ let muse = TempDir::new().unwrap();+ let data = TempDir::new().unwrap();+ let fresh = muse.path().join("fresh").join("settings.json");+ apply_to_muse_settings(+ &fresh,+ "http://memory:49374",+ None,+ data.path(),+ &muse_args(&fresh),+ )+ .unwrap();+ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&fresh).unwrap()).unwrap();+ assert_eq!(root["schema_version"], 1);++ let future = muse.path().join("future.json");+ fs::write(&future, r#"{"schema_version":2}"#).unwrap();+ apply_to_muse_settings(+ &future,+ "http://memory:49374",+ None,+ data.path(),+ &muse_args(&future),+ )+ .unwrap();+ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&future).unwrap()).unwrap();+ assert_eq!(root["schema_version"], 2);++ let broken = muse.path().join("broken.json");+ fs::write(&broken, r#"{"schema_version":1,"hooks":[]}"#).unwrap();+ assert!(+ apply_to_muse_settings(+ &broken,+ "http://memory:49374",+ None,+ data.path(),+ &muse_args(&broken)+ )+ .is_err()+ );+ assert_eq!(+ fs::read_to_string(&broken).unwrap(),+ r#"{"schema_version":1,"hooks":[]}"#+ );+ }++ /// The default Muse settings path comes from the captured environment:+ /// `XDG_CONFIG_HOME` when it is absolute.+ #[test]+ fn muse_settings_path_reads_xdg_config_home_from_the_runtime_env() {+ let env = crate::config::RuntimeEnv::with_process_env_for_tests(&[(+ "XDG_CONFIG_HOME",+ "/xdg-from-env",+ )]);+ assert_eq!(+ muse_settings_path(&env).unwrap(),+ Path::new("/xdg-from-env/muse/settings.json")+ );+ }++ /// `install-hooks --agent muse` infers the server and an explicit token+ /// from the bridge entry `install-mcp --client muse` writes, under either+ /// server map, and from an older streamable-HTTP entry; a `${...}`+ /// reference is never taken for a token.+ #[test]+ fn muse_mcp_inference_reads_the_bridge_entry_under_either_map() {+ let bridge = |key: &str, token: &str| {+ serde_json::json!({+ "schema_version": 1,+ key: {"ai-memory": {+ "type": "stdio",+ "command": "ai-memory",+ "args": ["mcp-bridge", "--agent", "muse", "--server-url", "http://memory:49374/mcp"],+ "env": {"AI_MEMORY_AUTH_TOKEN": token},+ "mode": "optional"+ }}+ })+ .to_string()+ };+ for key in ["mcpServers", "mcp_servers"] {+ let inferred = infer_muse_mcp_config(&bridge(key, "tok")).unwrap();+ assert_eq!(+ inferred.hook_server_url.as_deref(),+ Some("http://memory:49374"),+ "{key}"+ );+ assert_eq!(inferred.auth_token.as_deref(), Some("tok"), "{key}");+ }+ let reference =+ infer_muse_mcp_config(&bridge("mcpServers", "${AI_MEMORY_AUTH_TOKEN}")).unwrap();+ assert_eq!(reference.auth_token, None);+ let legacy = serde_json::json!({"mcp_servers": {"ai-memory": {+ "transport": "streamable_http",+ "url": "http://old:49374/mcp",+ "headers": {"Authorization": "Bearer old-token"}+ }}})+ .to_string();+ let inferred = infer_muse_mcp_config(&legacy).unwrap();+ assert_eq!(+ inferred.hook_server_url.as_deref(),+ Some("http://old:49374")+ );+ assert_eq!(inferred.auth_token.as_deref(), Some("old-token"));+ assert!(infer_muse_mcp_config(r#"{"mcpServers":{}}"#).is_none());+ assert_eq!(+ mcp_client_for_agent(AgentChoice::Muse),+ Some(McpClient::Muse)+ );+ }+/// Droid reads `settings.json`'s `hooks` only while `hooks.json` is/// absent, so creating `hooks.json` over them is refused and leaves both/// files untouched. Settings without hooks (the control), and adiff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 5234983e..a361eb38 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -48,11 +48,11 @@ enum JsonMcpLocation {RootServers,/// Top-level `context_servers` key used by Zed's settings.json.RootContextServers,- /// Top-level snake_case `mcp_servers` key used by Muse Code's- /// settings.json. Distinct from `RootMcpServers` purely by casing —- /// Muse documents `mcp_servers`, and the camelCase spelling every- /// other client uses would be ignored.- RootMcpServersSnake,+ /// Muse Code's settings.json: the top-level `mcpServers` map, or the+ /// legacy snake_case `mcp_servers` when the file already uses it. Muse+ /// drops the whole MCP block when both are present, so exactly one is+ /// ever written (see [`muse_servers_key`]).+ MuseServers,}/// Run the `install-mcp` subcommand.@@ -121,6 +121,14 @@ pub(crate) fn run_with_opencode_dialect(auth_token,..args};+ // Muse starts stdio servers with a cleared environment (`HOME`, `PATH`+ // and its own `MUSE_SESSION_ID`), so the bridge it launches finds this+ // install's config and token only through an explicit `--data-dir`, as+ // the Muse hooks do. Not from inside the Docker helper, whose data dir is+ // a container path the host-side bridge cannot open.+ if args.client == McpClient::Muse && config.runtime_env.host_cwd().is_none() {+ args.bridge_data_dir = Some(config.data_dir.clone());+ }if args.auth_token.is_none()&& let Some(token_file) = token_file{@@ -165,7 +173,8 @@ pub(crate) fn run_with_opencode_dialect(/// Wire a client to a server whose bearer lives in `[auth].bearer_token_file`/// without writing the token into the client's config.///-/// - Claude Code gets the session-aware `ai-memory mcp-bridge` entry.+/// - Claude Code gets the session-aware `ai-memory mcp-bridge` entry, and+/// Muse Code already has one (its entry is always the bridge)./// - Codex, Prime Agent and Droid reference `AI_MEMORY_AUTH_TOKEN` by name,/// the form their writers already use and each client documents./// - Pi is unchanged: its generated extension reads the hook credential file.@@ -180,7 +189,7 @@ fn route_file_token(args: &mut InstallMcpArgs, token_file: &Path) -> Result<()>match args.client {McpClient::ClaudeCode => args.session_aware = true,McpClient::Codex | McpClient::PrimeAgent | McpClient::Droid => args.token_env_var = true,- McpClient::Pi => {}+ McpClient::Pi | McpClient::Muse => {}McpClient::Zcode => bail!("this server's bearer token lives in {path} and ai-memory does not copy it into \another program's config. ZCode keeps only HTTP entries (`type`/`url`/`headers`), \@@ -292,15 +301,18 @@ pub(crate) fn existing_entry_endpoint(.map_err(|e| anyhow::anyhow!("parsing {}: {e}", path.display()))?.value.map_or(serde_json::Value::Null, Into::into);- let pointer = match location {- JsonMcpLocation::RootMcpServers => "/mcpServers",- JsonMcpLocation::RootMcp => "/mcp",- JsonMcpLocation::NestedMcpServers => "/mcp/servers",- JsonMcpLocation::RootServers => "/servers",- JsonMcpLocation::RootContextServers => "/context_servers",- JsonMcpLocation::RootMcpServersSnake => "/mcp_servers",+ let pointers: &[&str] = match location {+ JsonMcpLocation::RootMcpServers => &["/mcpServers"],+ JsonMcpLocation::RootMcp => &["/mcp"],+ JsonMcpLocation::NestedMcpServers => &["/mcp/servers"],+ JsonMcpLocation::RootServers => &["/servers"],+ JsonMcpLocation::RootContextServers => &["/context_servers"],+ JsonMcpLocation::MuseServers => &["/mcpServers", "/mcp_servers"],};- let Some(entry) = root.pointer(pointer).and_then(|servers| servers.get(name)) else {+ let Some(entry) = pointers+ .iter()+ .find_map(|pointer| root.pointer(pointer).and_then(|servers| servers.get(name)))+ else {return Ok(None);};if let Some(url) = ["url", "httpUrl", "serverUrl"]@@ -365,13 +377,6 @@ fn stdio_bridge_entry(args: &InstallMcpArgs) -> Option<serde_json::Value> {"command": BRIDGE_COMMAND,"args": bridge,}),- McpClient::Muse => json!({- "transport": "stdio",- "command": BRIDGE_COMMAND,- "args": bridge,- "enabled": true,- "mode": "optional",- }),McpClient::OpenCode => json!({"type": "local", "command": opencode_argv, "enabled": true}),McpClient::OpenCode2 => json!({"type": "local", "command": opencode_argv}),_ => return None,@@ -631,10 +636,9 @@ pub(crate) fn mcp_config_path_with(};zed_config_path_in(&config_dir, std::env::consts::OS)}- // Muse Code documents `~/.config/muse/settings.json`; it also reads- // $XDG_CONFIG_HOME for its skill roots, so --config-file covers- // non-default XDG setups (same policy as Zero above).- McpClient::Muse => home()?.join(".config").join("muse").join("settings.json"),+ // Muse Code keeps its user settings at+ // ${XDG_CONFIG_HOME:-~/.config}/muse/settings.json.+ McpClient::Muse => muse_settings_path_in(env("XDG_CONFIG_HOME"), home_dir())?,// Prime Agent's agent dir is $PRIME_AGENT_CODING_AGENT_DIR when set,// else ~/.prime/agent; user MCP servers live in its settings.json// (a project's `.prime/agent/settings.json` overrides it: pass that@@ -829,6 +833,30 @@ pub(crate) fn copilot_home_in(env_override: Option<std::ffi::OsString>) -> Resul.join(".copilot"))}+/// Meta Muse Code's user settings file,+/// `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`: the one file both its+/// hooks and its MCP servers live in. `XDG_CONFIG_HOME` counts only when set+/// to an absolute path, as the XDG base-directory spec requires; a blank or+/// relative value falls back to `<home>/.config`. Lexical only: the path is+/// never canonicalized.+///+/// # Errors+/// No usable `XDG_CONFIG_HOME` and no home directory.+pub(crate) fn muse_settings_path_in(+ xdg_config_home: Option<std::ffi::OsString>,+ home: Option<PathBuf>,+) -> Result<PathBuf> {+ let config_root = match crate::commands::path_util::agent_config_home(xdg_config_home)+ .filter(|dir| dir.is_absolute())+ {+ Some(dir) => dir,+ None => home+ .context("could not locate $HOME for ~/.config/muse/settings.json")?+ .join(".config"),+ };+ Ok(config_root.join("muse").join("settings.json"))+}+/// Factory Droid's user configuration root, `~/.factory`, under an injected/// home so path tests never consult the real one. Droid documents no/// variable that relocates it.@@ -1035,7 +1063,7 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {}McpClient::VsCodeCopilot => Some(JsonMcpLocation::RootServers),McpClient::Zed => Some(JsonMcpLocation::RootContextServers),- McpClient::Muse => Some(JsonMcpLocation::RootMcpServersSnake),+ McpClient::Muse => Some(JsonMcpLocation::MuseServers),McpClient::Codex | McpClient::Grok | McpClient::Pi | McpClient::Dsh => None,}}@@ -1379,12 +1407,14 @@ fn upsert_json_mcp_entry(.context("`context_servers` is present but not an object")?;servers.insert(args.name.clone(), entry);}- JsonMcpLocation::RootMcpServersSnake => {+ JsonMcpLocation::MuseServers => {+ let key = muse_servers_key(root)?;+ let entry = muse_entry_for_key(entry, key);let servers = root- .entry("mcp_servers")+ .entry(key).or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())).as_object_mut()- .context("`mcp_servers` is present but not an object")?;+ .with_context(|| format!("`{key}` is present but not an object"))?;servers.insert(args.name.clone(), entry);}}@@ -1422,9 +1452,9 @@ fn render_json_mcp_fragment(args: &InstallMcpArgs) -> Result<String> {// `schema_version` rides along: a hand-merged Muse settings.json// without it fails every command at startup, so the printed// snippet has to carry the key the same way --apply does.- JsonMcpLocation::RootMcpServersSnake => json!({+ JsonMcpLocation::MuseServers => json!({"schema_version": 1,- "mcp_servers": { args.name.as_str(): entry }+ "mcpServers": { args.name.as_str(): entry }}),};Ok(serde_json::to_string_pretty(&fragment)?)@@ -1737,29 +1767,83 @@ fn build_mcp_entry_zcode(args: &InstallMcpArgs) -> Result<serde_json::Value> {Ok(serde_json::Value::Object(entry))}-/// Muse Code MCP entry: `transport: "streamable_http"` + `url` + optional-/// `headers` under `~/.config/muse/settings.json`'s `mcp_servers` map.+/// Muse Code MCP entry, in the `mcpServers` shape: a stdio+/// `ai-memory mcp-bridge --agent muse` that forwards the `MUSE_SESSION_ID`+/// Muse gives its stdio servers as the actor session id, so unscoped calls+/// follow the session's own project. A streamable-HTTP entry would carry no+/// session id at all. [`muse_entry_for_key`] renames `type` to `transport`+/// for a file that keeps the legacy `mcp_servers` map.///-/// `mode` is written explicitly because Muse Code defaults it to-/// `required`, and a required server that fails to start aborts the whole-/// run. Memory is an augmentation, so an unreachable server should cost-/// the user their recall, not their coding session. No `framing` key is-/// emitted: a non-default `framing` on `streamable_http` fails Muse's own-/// validation.+/// Muse starts stdio servers with a cleared environment, so the entry names+/// the install's data dir (`--data-dir`, when [`InstallMcpArgs::bridge_data_dir`]+/// is set) and the bridge reads its bearer from that install's config+/// (`[auth].bearer_token_file`) at launch; a token given explicitly is+/// passed in `env` the way Claude Code's session-aware entry carries it. `mode` is written+/// explicitly because Muse defaults it to `required`, which aborts the whole+/// run when the server cannot start; ai-memory augments a session and must+/// never gate it.fn build_mcp_entry_muse(args: &InstallMcpArgs) -> Result<serde_json::Value> {- let bearer = bearer_header_value(args.auth_token.as_deref());- let server_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);+ let base_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);let mut entry = serde_json::Map::new();- entry.insert("transport".into(), json!("streamable_http"));- entry.insert("url".into(), json!(server_url));- if let Some(b) = bearer {- entry.insert("headers".into(), json!({"Authorization": b}));+ entry.insert("type".into(), json!("stdio"));+ entry.insert("command".into(), json!(BRIDGE_COMMAND));+ let mut argv = vec![+ json!("mcp-bridge"),+ json!("--agent"),+ json!("muse"),+ json!("--server-url"),+ json!(base_url),+ ];+ if let Some(data_dir) = &args.bridge_data_dir {+ argv.push(json!("--data-dir"));+ argv.push(json!(data_dir.to_string_lossy()));+ }+ entry.insert("args".into(), serde_json::Value::Array(argv));+ if let Some(token) = &args.auth_token {+ entry.insert("env".into(), json!({"AI_MEMORY_AUTH_TOKEN": token}));}- entry.insert("enabled".into(), json!(true));entry.insert("mode".into(), json!("optional"));Ok(serde_json::Value::Object(entry))}+/// The server map a Muse settings file takes ai-memory's entry under: the+/// legacy `mcp_servers` when the file already has it, else `mcpServers`.+/// Muse drops its whole MCP block when both keys are present, so adding the+/// second would disconnect every server the user has; a file that already+/// holds both is refused.+///+/// # Errors+/// Both keys are present.+fn muse_servers_key(root: &serde_json::Map<String, serde_json::Value>) -> Result<&'static str> {+ match (+ root.contains_key("mcpServers"),+ root.contains_key("mcp_servers"),+ ) {+ (true, true) => bail!(+ "this Muse settings file has both `mcpServers` and `mcp_servers`, and Muse ignores \+ every MCP server when both are present. Move the servers into one of the two maps \+ and re-run this command."+ ),+ (false, true) => Ok("mcp_servers"),+ _ => Ok("mcpServers"),+ }+}++/// [`build_mcp_entry_muse`]'s entry for the map it goes under: the legacy+/// `mcp_servers` names the transport `transport`, `mcpServers` names it+/// `type`.+fn muse_entry_for_key(entry: serde_json::Value, key: &str) -> serde_json::Value {+ let serde_json::Value::Object(mut entry) = entry else {+ return entry;+ };+ if key == "mcp_servers"+ && let Some(kind) = entry.remove("type")+ {+ entry.insert("transport".into(), kind);+ }+ serde_json::Value::Object(entry)+}+/// Insert / replace `[mcp_servers.<name>]` in a Codex `config.toml`.////// Codex parses both forms (block-style `[mcp_servers.foo]` and the@@ -2128,16 +2212,29 @@ fn render_zcode(args: &InstallMcpArgs) -> Result<String> {}fn render_muse(args: &InstallMcpArgs) -> Result<String> {+ let token_note = if args.auth_token.is_some() {+ "# The entry carries the token in `env`; treat settings.json as\n\+ # sensitive (chmod 600).\n"+ } else {+ ""+ };Ok(format!(- "# Muse Code (Meta) — merge into ~/.config/muse/settings.json\n\+ "# Meta Muse Code — merge into ${{XDG_CONFIG_HOME:-~/.config}}/muse/settings.json\n\# (or re-run this command with --apply), then start a new session.\n\#\n\# Keep \"schema_version\": 1 — without it every muse command fails\n\# at startup with `malformed settings file`.\n\#\n\- # mode is set to \"optional\" on purpose: Muse defaults it to\n\- # \"required\", which aborts the whole run when the server is\n\- # unreachable. Auth goes in the headers map.\n\+ # If the file already keeps its servers under the legacy `mcp_servers`\n\+ # map, put the entry there instead, with `\"transport\": \"stdio\"` in\n\+ # place of `\"type\": \"stdio\"`: Muse ignores every MCP server when both\n\+ # maps are present.\n\+ #\n\+ # The bridge forwards MUSE_SESSION_ID, so unscoped memory calls follow\n\+ # the session's project. mode is \"optional\" on purpose: Muse defaults\n\+ # it to \"required\", which aborts the whole run when the server cannot\n\+ # start. Pair with `ai-memory install-hooks --agent muse` for capture.\n\+ {token_note}\{snippet}\n",snippet = render_json_mcp_fragment(args)?,))@@ -2468,6 +2565,7 @@ mod tests {flavor: None,token_env_var: false,stdio_bridge: false,+ bridge_data_dir: None,}}@@ -2483,6 +2581,7 @@ mod tests {flavor: None,token_env_var: false,stdio_bridge: false,+ bridge_data_dir: None,}}@@ -2561,23 +2660,42 @@ mod tests {}}+ /// Muse's entry is the session-aware stdio bridge for `--agent muse`, so+ /// Muse forwards `MUSE_SESSION_ID`; a streamable-HTTP entry would carry no+ /// session id. `mode` is `optional` because Muse's default `required`+ /// aborts the whole run when the server cannot start. An explicit token+ /// rides `env`, never the command line.#[test]- fn muse_entry_uses_documented_streamable_http_shape() {- let entry = build_json_mcp_entry(&args_with_token(McpClient::Muse)).unwrap();-- assert_eq!(entry["transport"], "streamable_http");- assert_eq!(entry["url"], "http://127.0.0.1:49374/mcp");+ fn muse_entry_is_the_session_aware_bridge() {+ let entry = build_json_mcp_entry(&args_for(McpClient::Muse)).unwrap();assert_eq!(- entry["headers"]["Authorization"],- "Bearer test-token-deadbeef"+ entry,+ json!({+ "type": "stdio",+ "command": "ai-memory",+ "args": ["mcp-bridge", "--agent", "muse", "--server-url", "http://127.0.0.1:49374/mcp"],+ "mode": "optional",+ }));- assert_eq!(entry["enabled"], true);- // `required` is Muse's default and aborts the entire run when the- // memory server is unreachable.- assert_eq!(entry["mode"], "optional");- // A non-default `framing` on streamable_http fails Muse validation,- // so the entry must not carry the key at all.- assert!(entry.get("framing").is_none(), "{entry:#}");+ let with_token = build_json_mcp_entry(&args_with_token(McpClient::Muse)).unwrap();+ assert_eq!(+ with_token["env"]["AI_MEMORY_AUTH_TOKEN"],+ "test-token-deadbeef"+ );+ assert!(+ !with_token["args"].to_string().contains("test-token"),+ "{with_token:#}"+ );+ assert!(bridge_entry_url(&entry).is_some());++ // Muse clears the environment of its stdio servers, so the install's+ // data dir rides the entry.+ let mut args = args_for(McpClient::Muse);+ args.bridge_data_dir = Some(PathBuf::from("/srv/ai-memory"));+ let baked = build_json_mcp_entry(&args).unwrap();+ assert_eq!(baked["args"][5], "--data-dir");+ assert_eq!(baked["args"][6], "/srv/ai-memory");+ assert_eq!(bridge_entry_url(&baked), Some("http://127.0.0.1:49374/mcp"));}#[test]@@ -2585,8 +2703,8 @@ mod tests {let mut root = serde_json::Map::new();root.insert("telemetry".into(), json!({"enabled": false}));root.insert(- "mcp_servers".into(),- json!({"my-tools": {"transport": "stdio", "command": "my-mcp-server"}}),+ "hooks".into(),+ json!({"Stop": [{"hooks": [{"type": "command", "command": "notify"}]}]}),);upsert_json_mcp_entry(&mut root, &args_for(McpClient::Muse)).unwrap();@@ -2594,10 +2712,115 @@ mod tests {// Without this key every muse command fails at startup.assert_eq!(root["schema_version"], 1);assert_eq!(root["telemetry"]["enabled"], false);- assert_eq!(root["mcp_servers"]["my-tools"]["command"], "my-mcp-server");+ assert_eq!(root["hooks"]["Stop"][0]["hooks"][0]["command"], "notify");+ assert_eq!(root["mcpServers"]["ai-memory"]["type"], "stdio");+ assert!(!root.contains_key("mcp_servers"), "{root:#?}");+ }++ /// Adversarial: Muse drops every MCP server when `mcpServers` and the+ /// legacy `mcp_servers` are both present. A file that keeps the legacy+ /// map gets the entry there (in its `transport` spelling) and never a+ /// second map; a file that already has both is refused and left as it+ /// was. Control: a file with neither gets `mcpServers`.+ #[test]+ fn muse_upsert_writes_exactly_one_server_map() {+ let mut legacy = serde_json::Map::new();+ legacy.insert("schema_version".into(), json!(1));+ legacy.insert(+ "mcp_servers".into(),+ json!({"my-tools": {"transport": "stdio", "command": "my-mcp-server"}}),+ );+ upsert_json_mcp_entry(&mut legacy, &args_for(McpClient::Muse)).unwrap();+ assert!(!legacy.contains_key("mcpServers"), "{legacy:#?}");+ let ours = &legacy["mcp_servers"]["ai-memory"];+ assert_eq!(ours["transport"], "stdio");+ assert!(ours.get("type").is_none(), "{ours:#}");+ assert_eq!(ours["mode"], "optional");+ assert_eq!(+ legacy["mcp_servers"]["my-tools"]["command"],+ "my-mcp-server"+ );++ let mut both = serde_json::Map::new();+ both.insert("mcpServers".into(), json!({"a": {"type": "stdio"}}));+ both.insert("mcp_servers".into(), json!({"b": {"transport": "stdio"}}));+ let before = both.clone();+ let error = upsert_json_mcp_entry(&mut both, &args_for(McpClient::Muse)).unwrap_err();+ assert!(error.to_string().contains("both"), "{error:#}");+ assert_eq!(both, before, "a refused file is not touched");++ let mut empty = serde_json::Map::new();+ upsert_json_mcp_entry(&mut empty, &args_for(McpClient::Muse)).unwrap();+ assert!(empty.contains_key("mcpServers"));+ assert!(!empty.contains_key("mcp_servers"));+ }++ /// `--apply` against a real file: idempotent, keeps unknown keys and the+ /// user's own hooks, writes the bridge, and refuses (leaving the file+ /// byte-identical) when both server maps are present. The endpoint is read+ /// back from either map.+ #[test]+ fn muse_apply_is_idempotent_and_refuses_both_server_maps() {+ let tmp = tempfile::tempdir().unwrap();+ let file = tmp.path().join("settings.json");+ std::fs::write(+ &file,+ r#"{"schema_version":1,"theme":"dark","mcp_servers":{"x":{"transport":"stdio","command":"x"}}}"#,+ )+ .unwrap();+ let mut args = args_for(McpClient::Muse);+ args.apply = true;+ args.config_file = Some(file.clone());+ args.server_url = Some(DEFAULT_MCP_URL.into());+ apply_to_config_file(&args).unwrap();+ let first = std::fs::read_to_string(&file).unwrap();+ apply_to_config_file(&args).unwrap();+ assert_eq!(std::fs::read_to_string(&file).unwrap(), first);+ let root: serde_json::Value = serde_json::from_str(&first).unwrap();+ assert_eq!(root["theme"], "dark");+ assert_eq!(root["mcp_servers"]["ai-memory"]["args"][2], "muse");+ assert!(root.get("mcpServers").is_none());+ assert_eq!(+ existing_entry_endpoint(McpClient::Muse, &file, "ai-memory")+ .unwrap()+ .as_deref(),+ Some(DEFAULT_MCP_URL)+ );++ let both = tmp.path().join("both.json");+ let text = r#"{"schema_version":1,"mcpServers":{},"mcp_servers":{}}"#;+ std::fs::write(&both, text).unwrap();+ args.config_file = Some(both.clone());+ assert!(apply_to_config_file(&args).is_err());+ assert_eq!(std::fs::read_to_string(&both).unwrap(), text);+ }++ /// Muse resolves its settings under `XDG_CONFIG_HOME` when that is an+ /// absolute path, else under `~/.config`; a blank or relative value is+ /// ignored.+ #[test]+ fn muse_settings_path_follows_xdg_config_home() {+ let home = Some(PathBuf::from("/home/u"));assert_eq!(- root["mcp_servers"]["ai-memory"]["transport"],- "streamable_http"+ muse_settings_path_in(None, home.clone()).unwrap(),+ Path::new("/home/u/.config/muse/settings.json")+ );+ assert_eq!(+ muse_settings_path_in(Some("/xdg".into()), home.clone()).unwrap(),+ Path::new("/xdg/muse/settings.json")+ );+ for ignored in ["", " ", "relative/dir"] {+ assert_eq!(+ muse_settings_path_in(Some(ignored.into()), home.clone()).unwrap(),+ Path::new("/home/u/.config/muse/settings.json"),+ "{ignored:?}"+ );+ }+ assert!(muse_settings_path_in(None, None).is_err());+ let env = |name: &str| (name == "XDG_CONFIG_HOME").then(|| "/xdg2".into());+ assert_eq!(+ mcp_config_path_with(McpClient::Muse, &env).unwrap(),+ Path::new("/xdg2/muse/settings.json"));}@@ -2618,8 +2841,9 @@ mod tests {let rendered = render_muse(&args_for(McpClient::Muse)).unwrap();assert!(rendered.contains("\"schema_version\": 1"), "{rendered}");- assert!(rendered.contains("\"mcp_servers\""), "{rendered}");- assert!(!rendered.contains("\"mcpServers\""), "{rendered}");+ assert!(rendered.contains("\"mcpServers\""), "{rendered}");+ assert!(rendered.contains("\"--agent\""), "{rendered}");+ assert!(rendered.contains("\"optional\""), "{rendered}");}#[test]@@ -3799,8 +4023,8 @@ mod tests {assert!(text.contains("mcp-bridge"), "{client:?}: {text}");assert_eq!(text.contains("--no-session-id"),- client != McpClient::ClaudeCode,- "only Claude Code forwards a session id: {text}"+ !matches!(client, McpClient::ClaudeCode | McpClient::Muse),+ "only Claude Code and Muse forward a session id: {text}");}}@@ -3824,7 +4048,6 @@ mod tests {assert_eq!(entry(McpClient::CopilotCli)["type"], "local");assert_eq!(entry(McpClient::CopilotCli)["tools"][0], "*");assert_eq!(entry(McpClient::CommandCode)["transport"], "stdio");- assert_eq!(entry(McpClient::Muse)["mode"], "optional");assert_eq!(entry(McpClient::VsCodeCopilot)["type"], "stdio");assert!(entry(McpClient::Zed).get("type").is_none());// Kimi Code's schema dialect rides the bridge's upstream URL.diff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rsindex 3835caed..e33c3ec4 100644--- a/crates/ai-memory-cli/src/commands/mcp_bridge.rs+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs@@ -2,12 +2,17 @@//!//! Two modes, chosen by the entry that launches it, never by the environment://!-//! - **Session-aware** (the default, `install-mcp --client claude-code`):-//! forwards Claude Code's `CLAUDE_CODE_SESSION_ID` as+//! - **Session-aware** (the default, `install-mcp --client claude-code` and+//! `--client muse`): forwards the launching harness's session id as//! `X-Memory-Actor-Session-Id` on every upstream request, and refuses to-//! start without it. That refusal is deliberate (`docs/auto-scope.md`): a-//! registration installed to give Claude Code per-session routing must not-//! silently degrade to the shared single slot when the id is missing.+//! start without it. `--agent` names that harness and so the one variable+//! read: `claude-code` (the default) reads `CLAUDE_CODE_SESSION_ID`,+//! `muse` reads `MUSE_SESSION_ID`. No variable wins over another: the+//! other one is never consulted, so a Claude Code started from a Muse shell+//! (or the reverse) cannot forward the outer harness's id. The refusal is+//! deliberate (`docs/auto-scope.md`): a registration installed to give a+//! client per-session routing must not silently degrade to the shared+//! single slot when the id is missing.//! - **Session-less** (`--no-session-id`, every other client): a plain//! stdio-to-HTTP relay that forwards no session identity, so the client//! is a static MCP client and passes `workspace` + `project` explicitly,@@ -33,7 +38,7 @@ use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfiguse rmcp::transport::{StreamableHttpClientTransport, stdio};use rmcp::{ErrorData as McpError, Peer, ServerHandler, ServiceExt};-use crate::cli::McpBridgeArgs;+use crate::cli::{BridgeAgent, McpBridgeArgs};use crate::commands::install_mcp::mcp_server_url_from_base;use crate::config::Config;@@ -96,9 +101,8 @@ pub(crate) fn upstream_config(if let Some(session_id) = session_id {headers.insert(ACTOR_SESSION_HEADER,- HeaderValue::from_str(session_id).context(- "CLAUDE_CODE_SESSION_ID contains characters that are invalid in an HTTP header",- )?,+ HeaderValue::from_str(session_id)+ .context("the session id contains characters that are invalid in an HTTP header")?,);}@@ -110,19 +114,33 @@ pub(crate) fn upstream_config(Ok(config)}-/// The session id to forward: the inherited `CLAUDE_CODE_SESSION_ID` in the-/// session-aware mode, which refuses to run without one, and nothing at all-/// in the session-less mode, whatever the environment holds (see the module-/// docs for why an inherited id must not be forwarded there).-fn bridge_session_id(inherited: Option<&str>, no_session_id: bool) -> Result<Option<&str>> {+/// The session id to forward: in the session-aware mode, the one `agent`+/// sets (`CLAUDE_CODE_SESSION_ID` or `MUSE_SESSION_ID`), refusing to run+/// without it; in the session-less mode nothing at all, whatever the+/// environment holds (see the module docs for why an inherited id must not be+/// forwarded there).+fn bridge_session_id(+ env: &crate::config::RuntimeEnv,+ agent: BridgeAgent,+ no_session_id: bool,+) -> Result<Option<&str>> {if no_session_id {return Ok(None);}- inherited.map(Some).context(- "CLAUDE_CODE_SESSION_ID is missing; this session-aware bridge must be launched by \- Claude Code as an stdio MCP server (other clients register it with \- `--no-session-id`)",- )+ let inherited = match agent {+ BridgeAgent::ClaudeCode => env.claude_code_session_id(),+ BridgeAgent::Muse => env.muse_session_id(),+ };+ let (variable, harness) = match agent {+ BridgeAgent::ClaudeCode => (agent.session_env(), "Claude Code"),+ BridgeAgent::Muse => (agent.session_env(), "Muse Code"),+ };+ inherited.map(Some).with_context(|| {+ format!(+ "{variable} is missing; this session-aware bridge must be launched by {harness} \+ as an stdio MCP server (other clients register it with `--no-session-id`)"+ )+ })}/// Install a process-wide rustls crypto provider before the bridge opens an HTTPS@@ -164,10 +182,7 @@ fn bridge_base_url<'a>(flag: Option<&'a str>, configured: &'a str) -> &'a str {/// connection to a server that requires a token included), or either/// transport fails.pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {- let session_id = bridge_session_id(- config.runtime_env.claude_code_session_id(),- args.no_session_id,- )?;+ let session_id = bridge_session_id(&config.runtime_env, args.agent, args.no_session_id)?;let server_url = mcp_server_url_from_base(bridge_base_url(args.server_url.as_deref(),&config.server_url,@@ -221,7 +236,7 @@ pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {downstream.waiting().await- .context("waiting for Claude Code stdio MCP transport")?;+ .context("waiting for the stdio MCP client transport")?;upstream.close().await@@ -279,6 +294,7 @@ mod tests {assert!(rustls::crypto::CryptoProvider::get_default().is_some());}use super::*;+ use crate::config::RuntimeEnv;use std::sync::{Arc, Mutex};use axum::Router;@@ -374,6 +390,7 @@ mod tests {McpBridgeArgs {server_url: Some("https://memory.example/mcp".into()),no_session_id: false,+ agent: BridgeAgent::ClaudeCode,},).await@@ -391,10 +408,53 @@ mod tests {/// session-less mode never forwards one, not even an inherited id.#[test]fn only_the_session_aware_mode_forwards_and_requires_a_session_id() {- assert_eq!(bridge_session_id(Some("s"), false).unwrap(), Some("s"));- assert!(bridge_session_id(None, false).is_err());- assert_eq!(bridge_session_id(Some("inherited"), true).unwrap(), None);- assert_eq!(bridge_session_id(None, true).unwrap(), None);+ let claude = RuntimeEnv::with_session_ids_for_tests(Some("s"), None);+ let none = RuntimeEnv::default();+ let agent = BridgeAgent::ClaudeCode;+ assert_eq!(bridge_session_id(&claude, agent, false).unwrap(), Some("s"));+ assert!(bridge_session_id(&none, agent, false).is_err());+ assert_eq!(bridge_session_id(&claude, agent, true).unwrap(), None);+ assert_eq!(bridge_session_id(&none, agent, true).unwrap(), None);+ }++ /// Adversarial: `--agent` names the one variable read, so no harness's id+ /// stands in for another's. A Muse bridge forwards `MUSE_SESSION_ID` and+ /// never an inherited `CLAUDE_CODE_SESSION_ID`, and fails closed without+ /// its own id even when Claude's is set; a Claude bridge never forwards a+ /// `MUSE_SESSION_ID` it inherited from a Muse shell. Control: each+ /// forwards its own id when both are present, and the session-less mode+ /// forwards neither.+ #[test]+ fn each_harness_forwards_only_its_own_session_id() {+ let muse_id = "01a13669-dc61-7a72-b5ec-ad2f300ffd26";+ let both = RuntimeEnv::with_session_ids_for_tests(Some("claude-id"), Some(muse_id));+ assert_eq!(+ bridge_session_id(&both, BridgeAgent::Muse, false).unwrap(),+ Some(muse_id)+ );+ assert_eq!(+ bridge_session_id(&both, BridgeAgent::ClaudeCode, false).unwrap(),+ Some("claude-id")+ );++ let claude_only = RuntimeEnv::with_session_ids_for_tests(Some("claude-id"), None);+ let error = bridge_session_id(&claude_only, BridgeAgent::Muse, false).unwrap_err();+ assert!(+ error.to_string().contains("MUSE_SESSION_ID is missing"),+ "{error:#}"+ );+ let muse_only = RuntimeEnv::with_session_ids_for_tests(None, Some(muse_id));+ let error = bridge_session_id(&muse_only, BridgeAgent::ClaudeCode, false).unwrap_err();+ assert!(+ error+ .to_string()+ .contains("CLAUDE_CODE_SESSION_ID is missing"),+ "{error:#}"+ );+ assert_eq!(+ bridge_session_id(&both, BridgeAgent::Muse, true).unwrap(),+ None+ );}/// Session-less mode sends no session header at all, even when adiff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex da7bfbeb..9c755ef0 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -123,6 +123,34 @@ pub(crate) const DROID_EVENTS: [(&str, &str); 7] = [("SessionEnd", "session-end.sh"),];+/// Meta Muse Code lifecycle events ai-memory hooks. Each pair is+/// `(event-name-in-settings.json, native hook-event script stem)`; Muse has+/// no script bundle, so the `.sh` name only carries the event token the+/// native command is rendered with.+///+/// Claude Code's vocabulary plus `PostToolUseFailure`, which Muse fires+/// instead of `PostToolUse` when a tool fails (the server aliases it to+/// `post-tool-use` and reads the outcome from `error`). `SubagentStart` and+/// `SubagentStop` are left out: Muse Code 1.4.7 fires them for its built-in+/// reminder observers on every turn, each under its own session id, so wiring+/// them would open several empty sessions per prompt. Muse fires a real+/// `SessionEnd`, so no `finalize-session` step is needed.+pub(crate) const MUSE_EVENTS: [(&str, &str); 8] = [+ ("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"),+];++/// Seconds Muse waits for one ai-memory hook. Muse reads `timeout` in+/// seconds, like the Claude Code plugins it loads. The capture POST is+/// fire-and-forget; `SessionStart` also fetches a handoff.+pub(crate) const MUSE_HOOK_TIMEOUT_SECS: u64 = 30;+/// Kiro CLI v2-engine lifecycle events. Each pair is/// `(trigger-name-in-agent-config, POSIX hook-script-filename)`.///@@ -1069,6 +1097,48 @@ pub(crate) fn build_droid_hooks_payload()}+/// `{"hooks": <event map>}` for Meta Muse Code: the `hooks` key of+/// `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, in Claude Code's nested+/// shape with an empty matcher (every tool, every `SessionStart` source).+/// Muse runs each `command` through a shell with a cleared environment and+/// the Claude Code-shaped event JSON on stdin, so every entry invokes the+/// native `ai-memory hook` command with its server, data dir and agent baked+/// in; there is no script bundle, whatever `AI_MEMORY_HOOK_PLATFORM` asks+/// for. Each handler carries [`MUSE_HOOK_TIMEOUT_SECS`].+pub(crate) fn build_muse_hooks_payload(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Value {+ let mut payload = build_hook_payload_for_platform(+ &MUSE_EVENTS,+ Path::new(""),+ server_url,+ auth_token,+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::native(),+ "muse",+ data_dir,+ project_strategy,+ ),+ );+ if let Some(events) = payload.get_mut("hooks").and_then(Value::as_object_mut) {+ for groups in events.values_mut().filter_map(Value::as_array_mut) {+ for handler in groups+ .iter_mut()+ .filter_map(|group| group.get_mut("hooks").and_then(Value::as_array_mut))+ .flatten()+ .filter_map(Value::as_object_mut)+ {+ handler.insert("timeout".into(), Value::from(MUSE_HOOK_TIMEOUT_SECS));+ }+ }+ }+ payload+}+/// Pool (Poolside Agent CLI) `.poolside/settings.yaml` `hooks:` block for/// install-hooks' print path. Pool's hook config is a project-scoped YAML/// file at the repo root — there is no user-global hook file for ai-memorydiff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 231647dd..43c1d04b 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -411,6 +411,7 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrideflavor: None,token_env_var: false,stdio_bridge: false,+ bridge_data_dir: None,});WireInstalls {opencode_dialect,diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex bdcc8a0f..5da6194e 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -155,11 +155,15 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -let written_config = init_config_path(config, config_path);let agents = if args.agents.is_empty() {- detect_agents(+ let mut found = detect_agents(&home,&|harness| doctor::relocated_session_dir_with(harness, &env),&|client| install_mcp::mcp_config_path_with(client, &env).ok(),- )+ );+ if muse_detected(&home, &env) {+ found.push(AgentChoice::Muse);+ }+ found} else {dedup(args.agents.iter().copied())};@@ -246,6 +250,27 @@ fn detect_agents(dedup(found)}+/// Whether Meta Muse Code has run for this user: its config directory+/// (`${XDG_CONFIG_HOME:-~/.config}/muse`) or its data directory+/// (`${XDG_DATA_HOME:-~/.local/share}/muse`, where its sessions live) exists.+/// Muse has no native-session adapter, so it is found by these directories+/// rather than by [`detect_agents`]. Each XDG variable counts only when it is+/// an absolute path, lexically.+fn muse_detected(home: &Path, env: &dyn Fn(&str) -> Option<OsString>) -> bool {+ let xdg = |name: &str, fallback: &[&str]| {+ super::path_util::agent_config_home(env(name))+ .filter(|dir| dir.is_absolute())+ .unwrap_or_else(|| {+ fallback+ .iter()+ .fold(home.to_path_buf(), |dir, part| dir.join(part))+ })+ .join("muse")+ };+ xdg("XDG_CONFIG_HOME", &[".config"]).is_dir()+ || xdg("XDG_DATA_HOME", &[".local", "share"]).is_dir()+}+/// The binary path the service unit runs. A package manager's versioned/// location (a Homebrew `Cellar/<formula>/<version>` or a `/nix/store` path)/// disappears on the next upgrade or `brew cleanup` / garbage collection, so a@@ -580,6 +605,7 @@ fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<Strinflavor: None,token_env_var: false,stdio_bridge: false,+ bridge_data_dir: None,};if let Err(error) = install_mcp::run_with_opencode_dialect(config, args, dialect) {problems.push(format!("install-mcp: {error:#}"));@@ -693,6 +719,30 @@ mod tests {/// link that survives `brew upgrade` and `brew cleanup`, falling back to/// the `<prefix>/bin` link; a link to some other binary never wins.#[cfg(unix)]+ /// Muse is detected by its config or data directory under the home or+ /// the absolute XDG roots, and not otherwise.+ #[test]+ fn muse_is_detected_by_its_config_or_data_directory() {+ let none = |_: &str| -> Option<OsString> { None };+ let home = tempfile::tempdir().unwrap();+ assert!(!muse_detected(home.path(), &none));+ std::fs::create_dir_all(home.path().join(".local/share/muse/sessions")).unwrap();+ assert!(muse_detected(home.path(), &none));++ let home = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(home.path().join(".config/muse")).unwrap();+ assert!(muse_detected(home.path(), &none));++ let home = tempfile::tempdir().unwrap();+ let xdg = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(xdg.path().join("muse")).unwrap();+ let xdg_path = xdg.path().as_os_str().to_owned();+ let env = move |name: &str| (name == "XDG_CONFIG_HOME").then(|| xdg_path.clone());+ assert!(muse_detected(home.path(), &env));+ assert_eq!(skills_for(AgentChoice::Muse), InstallSkillsAgent::Agents);+ assert_eq!(AgentPlan::new(AgentChoice::Muse).mcp, Some(McpClient::Muse));+ }+#[test]fn a_cellar_binary_is_recorded_through_its_stable_homebrew_link() {use std::os::unix::fs::symlink;diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex c3f3b3ed..43f9ed82 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -120,6 +120,11 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {emit_droid(&args)?;return Ok(());}+ // Muse too: its settings.json hooks run the native `hook` command.+ if matches!(args.agent, AgentChoice::Muse) {+ emit_muse(&args)?;+ return Ok(());+ }let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};@@ -217,7 +222,8 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {| AgentChoice::Zero| AgentChoice::Zcode| AgentChoice::Hermes- | AgentChoice::Droid => {+ | AgentChoice::Droid+ | AgentChoice::Muse => {bail!("internal: generated integration should have returned before emitting staged hooks")@@ -341,6 +347,32 @@ fn emit_droid(args: &SetupAgentArgs) -> Result<()> {Ok(())}+/// Print the `hooks` block for Muse's `settings.json`. No scripts are staged:+/// each entry runs the ai-memory binary's native `hook` command with Muse's+/// event JSON on stdin, so the binary must be reachable on the host that runs+/// Muse.+fn emit_muse(args: &SetupAgentArgs) -> Result<()> {+ let payload = crate::commands::render_shared::build_muse_hooks_payload(+ &args.server_url,+ args.auth_token.as_deref(),+ None,+ None,+ );+ let serialized =+ serde_json::to_string_pretty(&payload["hooks"]).context("serializing Muse hook config")?;+ println!("# Meta Muse Code — merge under the `hooks` key of");+ println!("# ${{XDG_CONFIG_HOME:-~/.config}}/muse/settings.json, keeping its");+ println!("# \"schema_version\": 1. The `command` must be an ai-memory binary reachable");+ println!("# on the host that runs Muse; prefer `ai-memory install-hooks --agent muse");+ println!("# --apply` from that host so the path and data dir are resolved for you.");+ if args.auth_token.is_some() {+ println!("# Treat settings.json as sensitive (chmod 600).");+ }+ println!();+ println!("{serialized}");+ Ok(())+}+fn normalise_hook_server_url(url: &str) -> String {url.trim().trim_end_matches('/').to_string()}@@ -426,6 +458,7 @@ fn emit_extension_setup_hint(config: &Config, args: &SetupAgentArgs) -> Result<(flavor: None,token_env_var: false,stdio_bridge: false,+ bridge_data_dir: None,},Some(dialect),)?;diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 005b22fb..dad55be9 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -266,6 +266,12 @@ fn build_plan(install_hooks::droid_hooks_path()?,HookConfigShape::FlatHookFile,),+ // Muse keeps its hooks under the usual `hooks` key of the+ // settings.json its MCP servers live in, beside `schema_version`.+ (+ install_hooks::muse_settings_path(env)?,+ HookConfigShape::NestedHooksKey,+ ),]);for (path, shape) in hook_files {if !path.exists() {@@ -452,6 +458,8 @@ fn build_plan()} else if matches!(client, Omp) {omp_dirs.iter().map(|dir| dir.join("mcp.json")).collect()+ } else if matches!(client, Muse) {+ vec![install_hooks::muse_settings_path(env)?]} else {let Ok(path) = install_mcp::mcp_config_path(client) else {continue;@@ -1503,9 +1511,9 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {McpClient::Openclaw | McpClient::Zero | McpClient::Zcode => Some(&["mcp", "servers"]),McpClient::VsCodeCopilot => Some(&["servers"]),McpClient::Zed => Some(&["context_servers"]),- // Muse Code spells the key snake_case; the camelCase spelling the- // clients above use would leave the entry behind.- McpClient::Muse => Some(&["mcp_servers"]),+ // Muse reads `mcpServers` or the legacy `mcp_servers`;+ // `strip_mcp_json` sweeps both.+ McpClient::Muse => Some(&["mcpServers"]),McpClient::Codex | McpClient::Grok | McpClient::Pi | McpClient::Dsh => None,}}@@ -1647,40 +1655,59 @@ fn strip_mcp_json(let Some(path) = mcp_servers_path(client) else {return Ok((content.to_string(), Vec::new()));};+ let legacy: &[&str] = &["mcp_servers"];+ let paths: Vec<&[&str]> = if client == McpClient::Muse {+ vec![path, legacy]+ } else {+ vec![path]+ };let mut removed = Vec::new();let new_content = mutate_json(content, |root| {- let mut cursor: &mut serde_json::Map<String, serde_json::Value> = root;- for (depth, key) in path.iter().enumerate() {- let is_last = depth == path.len() - 1;- if is_last {- let Some(servers) = cursor.get_mut(*key).and_then(|v| v.as_object_mut()) else {- return Ok(());- };- let keys: Vec<String> = servers.keys().cloned().collect();- for k in keys {- let ours = servers- .get(&k)- .is_some_and(|e| mcp_entry_is_ours(&k, e, name, url));- if ours {- servers.remove(&k);- removed.push(k);- }- }- if servers.is_empty() {- cursor.remove(*key);- }- } else {- let Some(next) = cursor.get_mut(*key).and_then(|v| v.as_object_mut()) else {- return Ok(());- };- cursor = next;- }+ for path in &paths {+ strip_mcp_json_at(root, path, name, url, &mut removed);}Ok(())})?;Ok((new_content, removed))}+/// [`strip_mcp_json`] for the server map at one key path.+fn strip_mcp_json_at(+ root: &mut serde_json::Map<String, serde_json::Value>,+ path: &[&str],+ name: Option<&str>,+ url: &str,+ removed: &mut Vec<String>,+) {+ let mut cursor: &mut serde_json::Map<String, serde_json::Value> = root;+ for (depth, key) in path.iter().enumerate() {+ let is_last = depth == path.len() - 1;+ if is_last {+ let Some(servers) = cursor.get_mut(*key).and_then(|v| v.as_object_mut()) else {+ return;+ };+ let keys: Vec<String> = servers.keys().cloned().collect();+ for k in keys {+ let ours = servers+ .get(&k)+ .is_some_and(|e| mcp_entry_is_ours(&k, e, name, url));+ if ours {+ servers.remove(&k);+ removed.push(k);+ }+ }+ if servers.is_empty() {+ cursor.remove(*key);+ }+ } else {+ let Some(next) = cursor.get_mut(*key).and_then(|v| v.as_object_mut()) else {+ return;+ };+ cursor = next;+ }+ }+}+/// Remove ai-memory's Codex MCP table by name or `url`. Returns new/// content and removed names. Preserves comments + other tables.fn strip_mcp_toml(content: &str, name: Option<&str>, url: &str) -> Result<(String, Vec<String>)> {diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 817fa74e..3d6c228f 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -695,6 +695,7 @@ pub struct RuntimeEnv {process_env: CapturedProcessEnv,capture_owner_active: bool,claude_code_session_id: Option<String>,+ muse_session_id: Option<String>,anthropic_api_key: Option<SecretString>,anthropic_oauth_token: Option<SecretString>,openai_api_key: Option<SecretString>,@@ -745,6 +746,7 @@ impl RuntimeEnv {capture_owner_active: env_string("AI_MEMORY_CAPTURE_OWNER").is_some_and(|value| !value.trim().is_empty()),claude_code_session_id: env_string("CLAUDE_CODE_SESSION_ID"),+ muse_session_id: env_string("MUSE_SESSION_ID"),anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),// CLAUDE_CODE_OAUTH_TOKEN is the name Claude Code reads the// `claude setup-token` token from; ANTHROPIC_OAUTH_TOKEN is our@@ -847,6 +849,13 @@ impl RuntimeEnv {self.claude_code_session_id.as_deref()}+ /// Meta Muse Code session id, which Muse sets for its stdio MCP servers+ /// and hooks.+ #[must_use]+ pub fn muse_session_id(&self) -> Option<&str> {+ self.muse_session_id.as_deref()+ }+/// Hook-spool attempt override captured from the process environment.#[must_use]pub fn hook_spool_max_attempts(&self) -> Option<&str> {@@ -880,6 +889,15 @@ impl RuntimeEnv {}}+ #[cfg(test)]+ pub fn with_session_ids_for_tests(claude_code: Option<&str>, muse: Option<&str>) -> Self {+ Self {+ claude_code_session_id: claude_code.map(str::to_owned),+ muse_session_id: muse.map(str::to_owned),+ ..Self::default()+ }+ }+#[cfg(test)]pub fn with_process_env_for_tests(pairs: &[(&str, &str)]) -> Self {Self {diff --git a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rsindex d5bb705a..943d6d58 100644--- a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs@@ -87,6 +87,7 @@ mod slow {// A developer (or agent) running these tests from Claude Code// has its session id exported; a child must not inherit it..env_remove("CLAUDE_CODE_SESSION_ID")+ .env_remove("MUSE_SESSION_ID").current_dir(&self.home);cmd}@@ -648,6 +649,21 @@ mod slow {"the session-aware mode keeps failing closed: {}",String::from_utf8_lossy(&out.stderr));+ // Muse's bridge reads only MUSE_SESSION_ID: an inherited Claude id+ // does not stand in for it.+ let mut muse = install.cmd();+ let out = muse+ .args(["mcp-bridge", "--agent", "muse", "--server-url", &base])+ .env("CLAUDE_CODE_SESSION_ID", "inherited-from-a-claude-terminal")+ .stdin(Stdio::null())+ .output()+ .unwrap();+ assert!(!out.status.success());+ assert!(+ String::from_utf8_lossy(&out.stderr).contains("MUSE_SESSION_ID is missing"),+ "the Muse bridge fails closed without its own id: {}",+ String::from_utf8_lossy(&out.stderr)+ );}/// A bridge with no token against an auth-on server exits at once withdiff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rsindex 3bfbf2e4..9457e1be 100644--- a/crates/ai-memory-cli/tests/suite/packaging.rs+++ b/crates/ai-memory-cli/tests/suite/packaging.rs@@ -487,6 +487,10 @@ fn docker_wrappers_keep_stdin_attached_independently_of_tty_allocation() {posix.contains("CLAUDE_CODE_SESSION_ID"),"POSIX wrapper must forward Claude's session id into the bridge container");+ assert!(+ posix.contains(" MUSE_SESSION_ID \\"),+ "POSIX wrapper must forward Muse's session id into the bridge container"+ );assert!(posix.contains("git -C \"${PWD}\" rev-parse --show-toplevel"));assert!(posix.contains("AI_MEMORY_SCOPE_CWD=/scope${SCOPE_REL}"));assert!(posix.contains("${SCOPE_ROOT}:/scope:ro"));@@ -508,6 +512,10 @@ fn docker_wrappers_keep_stdin_attached_independently_of_tty_allocation() {powershell.contains("\"CLAUDE_CODE_SESSION_ID\""),"PowerShell wrapper must forward Claude's session id into the bridge container");+ assert!(+ powershell.contains("\"MUSE_SESSION_ID\""),+ "PowerShell wrapper must forward Muse's session id into the bridge container"+ );assert!(powershell.contains("AI_MEMORY_SCOPE_CWD=$ScopeCwd"));assert!(powershell.contains("${ScopeRoot}:/scope:ro"));}diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rsindex 4a9a53af..84ceb5af 100644--- a/crates/ai-memory-cli/tests/suite/removal.rs+++ b/crates/ai-memory-cli/tests/suite/removal.rs@@ -2311,3 +2311,73 @@ fn uninstall_keeps_the_hook_bearer_unless_hooks_are_removed() {);}}++/// Meta Muse Code: `install-mcp` and `install-hooks` both merge into+/// `$XDG_CONFIG_HOME/muse/settings.json` around the user's own server and+/// hook, keeping `schema_version` and unknown keys, the MCP entry goes under+/// the legacy `mcp_servers` map the file already uses (never a second map),+/// and `uninstall` removes only ai-memory's entries.+#[test]+fn muse_install_and_uninstall_round_trip_preserves_user_entries() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let settings = home.path().join(".config/muse/settings.json");+ write_file(+ &settings,+ r#"{"schema_version":1,"theme":"dark","mcp_servers":{"other":{"transport":"stdio","command":"other-mcp","mode":"optional"}},"hooks":{"PreToolUse":[{"matcher":"bash","hooks":[{"type":"command","command":"/usr/local/bin/guard.sh","timeout":5}]}]}}"#,+ );++ for args in [+ &["install-mcp", "--client", "muse", "--apply"][..],+ &["install-hooks", "--agent", "muse", "--apply"][..],+ ] {+ let out = command_with_home(home.path()).args(args).output().unwrap();+ assert!(+ out.status.success(),+ "{args:?} failed: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ }+ let installed: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();+ assert_eq!(installed["schema_version"], 1);+ assert_eq!(installed["theme"], "dark");+ assert!(installed.get("mcpServers").is_none(), "{installed}");+ let ours = &installed["mcp_servers"]["ai-memory"];+ assert_eq!(ours["transport"], "stdio", "{installed}");+ assert_eq!(ours["mode"], "optional");+ assert_eq!(ours["args"][1], "--agent");+ assert_eq!(ours["args"][2], "muse");+ assert_eq!(installed["mcp_servers"]["other"]["command"], "other-mcp");+ let pre = installed["hooks"]["PreToolUse"].as_array().unwrap();+ assert_eq!(pre.len(), 2, "{installed}");+ assert!(+ pre[1]["hooks"][0]["command"]+ .as_str()+ .unwrap()+ .contains("--agent muse"),+ "{installed}"+ );+ assert!(installed["hooks"]["SessionEnd"].is_array(), "{installed}");++ let uninstall = command_with_home(home.path())+ .args(["uninstall", "--apply", "--yes"])+ .output()+ .unwrap();+ assert!(+ uninstall.status.success(),+ "uninstall failed: {}",+ String::from_utf8_lossy(&uninstall.stderr)+ );+ let text = std::fs::read_to_string(&settings).unwrap();+ assert!(!text.contains("--agent muse"), "{text}");+ assert!(!text.contains("mcp-bridge"), "{text}");+ let removed: serde_json::Value = serde_json::from_str(&text).unwrap();+ assert_eq!(removed["schema_version"], 1);+ assert_eq!(removed["theme"], "dark");+ assert_eq!(removed["mcp_servers"]["other"]["command"], "other-mcp");+ assert_eq!(+ removed["hooks"]["PreToolUse"][0]["hooks"][0]["command"],+ "/usr/local/bin/guard.sh"+ );+}diff --git a/crates/ai-memory-cli/tests/suite/setup_e2e.rs b/crates/ai-memory-cli/tests/suite/setup_e2e.rsindex 13f35c8b..7f9abff8 100644--- a/crates/ai-memory-cli/tests/suite/setup_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/setup_e2e.rs@@ -80,6 +80,7 @@ impl Sandbox {.env("AI_MEMORY_AUTO_IMPROVE__SCHEDULER__ENABLED", "false").env("RUST_LOG", "off").env_remove("CLAUDE_CODE_SESSION_ID")+ .env_remove("MUSE_SESSION_ID").current_dir(&self.home).stdin(Stdio::null());if let Some(port) = port {diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex c07836aa..6800826a 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -106,7 +106,7 @@ install or refresh work.If you're about to write a durable project rule ("always X", "neverY", "all PRs must ..."), write it in the project's canonical agent instruction file.Many projects use CLAUDE.md for Claude Code and-AGENTS.md for Codex / OpenCode / OpenCode 2 / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI / Command Code / GitHub Copilot CLI,+AGENTS.md for Codex / OpenCode / OpenCode 2 / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI / Command Code / GitHub Copilot CLI / Muse Code,but if the project says one file is canonical, use that file.Claude Code loads `CLAUDE.md` and does not read `AGENTS.md`. In a project@@ -128,7 +128,7 @@ latest binary's recommended copy:- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting in this project". The agent calls `memory_install_self_routing`,picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /- OpenCode / OpenCode 2 / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI / Command Code / Copilot CLI -> `AGENTS.md`),+ OpenCode / OpenCode 2 / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI / Command Code / Copilot CLI / Muse Code -> `AGENTS.md`),uses its Write / Edit tool to replace or append the returned`markered_block` while preservingnon-ai-memory user content, then writes or updates each returneddiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 9c9f93ef..69510a13 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -6226,6 +6226,7 @@ impl AiMemoryServer {"command_code": "AGENTS.md","grok": "AGENTS.md","copilot_cli": "AGENTS.md",+ "muse": "AGENTS.md","default": "AGENTS.md"},"managed_skills": managed_skills,@@ -8721,12 +8722,25 @@ mod tests {}}+ /// Muse Code reads `AGENTS.md` first and the cross-agent `.agents/skills`+ /// root, so the installed snippet routes it there.+ #[test]+ fn installed_prompt_surface_routes_muse_to_agents_md() {+ let installed = installed_ai_memory_prompt_surface();+ assert!(+ installed.contains("GitHub Copilot CLI / Muse Code")+ && installed.contains("Copilot CLI / Muse Code -> `AGENTS.md`")+ && installed.contains(".agents/skills"),+ "installed snippet must route Muse Code to AGENTS.md and .agents/skills"+ );+ }+#[test]fn installed_prompt_surface_routes_copilot_cli_to_agents_md() {let installed = installed_ai_memory_prompt_surface();assert!(installed.contains("GitHub Copilot CLI")- && installed.contains("Copilot CLI -> `AGENTS.md`")+ && installed.contains("Command Code / Copilot CLI / Muse Code -> `AGENTS.md`")&& installed.contains(".github/skills"),"installed snippet and managed skills must route Copilot CLI to AGENTS.md and .github/skills");diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e97bc1ab..28f844ec 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -675,11 +675,13 @@ server keeps the same auth, scope resolver, and tool handlers as direct HTTPclients. It has two modes, chosen by the entry that launches it:- session-aware (Claude Code, `install-mcp --client claude-code- --session-aware`, and every Claude Code entry on a token-file install): it- injects the inherited `CLAUDE_CODE_SESSION_ID` as- `X-Memory-Actor-Session-Id` and fails closed without one, so a- registration meant for per-session routing never silently degrades to the- shared slot;+ --session-aware`, and every Claude Code entry on a token-file install; and+ Meta Muse Code, whose entry is always `mcp-bridge --agent muse`): it+ injects the launching harness's inherited session id+ (`CLAUDE_CODE_SESSION_ID`, or `MUSE_SESSION_ID` with `--agent muse`, never+ the other one) as `X-Memory-Actor-Session-Id` and fails closed without it,+ so a registration meant for per-session routing never silently degrades to+ the shared slot;- session-less (`--no-session-id`, every other client on a token-fileinstall): it forwards no session identity and ignores an inherited`CLAUDE_CODE_SESSION_ID`, which a client started from a Claude Code@@ -1406,7 +1408,9 @@ needs a manual change.A token read from the file is never written into a harness config or onto acommand line. `install-mcp` gives Claude Code the session-aware-`ai-memory mcp-bridge` stdio entry, which reads the file itself; Codex,+`ai-memory mcp-bridge` stdio entry, which reads the file itself, and Meta Muse+Code always has one (`--agent muse`, with the install's `--data-dir` because+Muse clears the environment of its stdio servers); Codex,Prime Agent and Factory Droid reference `AI_MEMORY_AUTH_TOKEN` by name; every other client getsa stdio entry, in its own config format, for `ai-memory mcp-bridge--no-session-id`. ZCode keeps HTTP entries only and is refused.diff --git a/docs/auto-scope.md b/docs/auto-scope.mdindex 2f708366..3c1c1948 100644--- a/docs/auto-scope.md+++ b/docs/auto-scope.md@@ -186,6 +186,12 @@ subprocess the startup id rather than the resumed id. Restart Claude Code afterwhen no `CLAUDE_CODE_SESSION_ID` is available instead of silently degrading tothe shared single slot.+Meta Muse Code's entry is the same bridge with `--agent muse`: Muse gives its+stdio MCP servers `MUSE_SESSION_ID`, the session id its hooks report, and the+bridge forwards that one. Each mode reads only its own variable, so a Claude+Code started from a Muse shell (or the reverse) never forwards the outer+harness's id, and the Muse bridge also fails closed without `MUSE_SESSION_ID`.+The same binary also runs session-less, as `ai-memory mcp-bridge--no-session-id`: the stdio entry `install-mcp` writes for every other clientwhen the server's token lives in `[auth].bearer_token_file`. It forwards nodiff --git a/docs/install.md b/docs/install.mdindex 2e028088..b7ff9d97 100644--- a/docs/install.md+++ b/docs/install.md@@ -20,7 +20,7 @@ RPM, macOS menu bar app). This page covers everything else:- [macOS menu bar app](#macos-menu-bar-app)(self-contained `.app` + LaunchAgent)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, Command Code, Devin CLI, OpenCode, OpenCode 2, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, GitHub Copilot CLI, Factory Droid, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Pool, OpenClaw, VS Code Copilot, Zed, and MCP-only recipes for Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman)+ (Codex, Command Code, Devin CLI, OpenCode, OpenCode 2, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, GitHub Copilot CLI, Factory Droid, Meta Muse Code, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Pool, OpenClaw, VS Code Copilot, Zed, and MCP-only recipes for Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -245,6 +245,17 @@ configure ai-memory@ai-memory`:--agent droid` hooks deliver the same event (`~/.factory/hooks.json`, orthe `hooks` key of `~/.factory/settings.json` while `hooks.json` does notexist) the plugin skips it, as it does for Claude's settings hooks.+- Meta Muse Code reads `.claude-plugin/plugin.json` bundles, but Muse Code+ 1.4.7 refuses to install this one (`plugin declares a retained unsupported+ MCP boundary`) because its `.mcp.json` uses `${user_config.*}`+ placeholders; use `install-hooks --agent muse` and `install-mcp --client+ muse` instead. The launcher is ready for a Muse that loads it: it tells Muse+ apart by the `MUSE_PLUGIN_ID` and `MUSE_SESSION_ID` Muse sets for plugin+ hooks and records the events as `muse`, skips an event that+ `install-hooks --agent muse` hooks already deliver (a catch-all matcher+ under the `hooks` key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`),+ and drops the plugin's `SubagentStart` and `SubagentStop` events, which+ `install-hooks --agent muse` never wires.- On Windows, Claude Code runs plugin hooks through Git Bash, which italready requires, so the launcher needs nothing else.- With the Docker wrapper, plugin hooks need a `bin/ai-memory` wrapper that runs@@ -1708,6 +1719,77 @@ needed. Start a new droid session after installing so it loads the hooks.`ai-memory setup --agent droid` runs both installers; `setup` does not detectDroid on its own, and no managed workstream (`ai-memory run droid`) is claimed.+### Meta Muse Code++Muse Code (`muse`, also installed as `muse-code`) keeps its user settings in+`${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, one file for both its+hooks and its MCP servers. `install-hooks --agent muse` (aliases `muse-code`,+`musecode`) merges lifecycle hooks under its `hooks` key and+`install-mcp --client muse` merges the MCP entry, keeping+`"schema_version": 1`, every other key and every entry you already have:++```bash+ai-memory install-mcp --client muse --apply+ai-memory install-hooks --agent muse --apply+```++Muse fails every command at startup when `settings.json` has no+`schema_version`, so both installers add `"schema_version": 1` when it is+missing and never rewrite an existing value. Each `--apply` writes a backup+next to the file when it changes it, and running it again changes nothing.++Muse sends Claude Code-shaped JSON on stdin (`session_id`, `cwd`,+`tool_name`, `tool_input`, `tool_use_id`, `tool_response`), so each entry+runs the native `ai-memory hook --event … --agent muse` command with an empty+matcher and a 30-second `timeout`. There is no script bundle. Muse runs hooks+with a cleared environment (`HOME`, `PATH`, `PWD` and its own `MUSE_*`+variables), so the server URL and the data dir are written into each+command, and `AI_MEMORY_*` variables exported in your shell do not reach the+hooks; run the installer again after changing either. The local spool,+bearer auth and `[capture] ignore_paths` apply. Muse's `read_file`,+`write_file`, `edit_file`, `apply_patch`, `search`, `bash`, `monitor`,+`web_fetch` and memory tools map to the file, search and shell families+those exclusions use, and a relative `path` is resolved against the session's+`cwd`. A `project`-scope memory path lands under `.agents/memory/`; the+personal memory scopes live outside the repository and are stored as+metadata only while a `[capture]` marker is active.++Eight events are wired: `SessionStart`, `UserPromptSubmit`, `PreToolUse`,+`PostToolUse`, `PostToolUseFailure` (Muse fires it instead of `PostToolUse`+when a tool fails), `PreCompact`, `Stop` and `SessionEnd`. `SubagentStart` and+`SubagentStop` are left out: Muse fires them on every turn for its built-in+reminder observers, each under its own session id, so wiring them would+record several empty sessions per prompt. The `SessionStart` hook delivers the+prior session's handoff through `hookSpecificOutput.additionalContext`,+which Muse adds to the session as developer context, and Muse's own+`SessionEnd` closes the session, so `finalize-session` is not needed. With no+handoff to deliver, the `SessionStart` and `UserPromptSubmit` hooks print+nothing, since Muse adds that stdout to the model's context too.++The MCP entry is a stdio `ai-memory mcp-bridge --agent muse` with+`"mode": "optional"` (Muse's default `required` aborts the run when a server+cannot start). Muse gives its stdio servers `MUSE_SESSION_ID`, and the bridge+forwards it, so Muse is a session-aware client: unscoped memory calls follow+the session's own project. A streamable-HTTP entry would carry no session+id. The entry goes under `mcpServers`, or under the legacy `mcp_servers` map+when the file already has one, and never under both: Muse ignores every MCP+server when both maps are present, so `--apply` refuses a file that already+has both and `ai-memory doctor` reports it. The entry names the install's+data dir (`--data-dir`) because the bridge starts in Muse's cleared+environment, and the bridge reads the token from there; a token passed+explicitly with `--auth-token` goes in the entry's `env` instead, so treat the+file as private then. `ai-memory` must be on the `PATH` Muse starts with.++The ai-memory routing skills need no extra step: Muse reads+`~/.agents/skills`, which `install-skills` writes, and it reads `AGENTS.md`+first among the instruction files. `ai-memory setup` detects Muse by its+config or data directory and runs all three installers;+`ai-memory setup --agent muse` names it explicitly. Muse also reads a+project's `.muse/hooks.json` in a trusted workspace; ai-memory does not write+it, because its commands carry this machine's paths. No managed workstream+(`ai-memory run muse`) and no transcript backfill from+`${XDG_DATA_HOME:-~/.local/share}/muse/sessions` are claimed yet.+### Hermes Agent (Nous Research)Hermes declares lifecycle hooks in the `hooks:` block ofdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 20ab1914..ad4794f3 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -16,7 +16,8 @@ Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no> `[auth].bearer_token_file` (every fresh `ai-memory init`, and> `ai-memory auth enable`), `install-mcp` never writes it into a client's> config. Claude Code gets the session-aware `ai-memory mcp-bridge` stdio-> entry; Codex (`bearer_token_env_var`), Prime Agent (`bearerTokenEnvVar`) and+> entry, and Muse Code always gets one (`mcp-bridge --agent muse`, which reads+> the token file itself); Codex (`bearer_token_env_var`), Prime Agent (`bearerTokenEnvVar`) and> Factory Droid (`Bearer ${AI_MEMORY_AUTH_TOKEN}` in `headers`) name> `AI_MEMORY_AUTH_TOKEN`, which you export where you start them. Every> other client gets a local stdio entry, in its own format, that runs@@ -78,7 +79,7 @@ manual container/script extraction and explicit compatibility overrides.Reinstall/refresh an existing hook or plugin to gain it; see[Capture exclusions](marker-file.md#capture-exclusions).-Claude Desktop's ordinary Chat surface, VS Code Copilot, Zed, and Muse Code+Claude Desktop's ordinary Chat surface, VS Code Copilot and Zedare **MCP-only** here:they expose long-term memory to their LLMs via ai-memory's MCP tools(`memory_query`, `memory_recent`, `memory_handoff_accept`, etc.), but@@ -509,55 +510,66 @@ Sources: <https://zed.dev/docs/ai/mcp>,## Muse Code-**Status:** MCP supported through Muse Code's native streamable-HTTP-transport, including bearer authentication. No lifecycle-hook integration-and no managed-workstream adapter.+**Status:** MCP and lifecycle hooks are supported. The MCP entry is a+session-aware stdio bridge, the `SessionStart` hook injects the pending+handoff, and Muse's `SessionEnd` closes the session. No managed workstream.-**Config file:** `~/.config/muse/settings.json`. Muse also reads-`$XDG_CONFIG_HOME` for its skill roots; on a non-default XDG setup pass the-concrete path with `--config-file`.+**Config file:** `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, the same+file `install-hooks --agent muse` writes its hooks into.-Servers live under the top-level snake_case `mcp_servers` key. Note the-casing: `mcpServers`, which most other clients use, is ignored here.+```bash+ai-memory install-mcp --client muse --apply+ai-memory install-hooks --agent muse --apply+```++Muse gives its stdio MCP servers `MUSE_SESSION_ID`, while a streamable-HTTP+entry carries no session id, so the entry runs the bridge, which forwards that+id as the actor session:```json{"schema_version": 1,- "mcp_servers": {+ "mcpServers": {"ai-memory": {- "transport": "streamable_http",- "url": "http://127.0.0.1:49374/mcp",- "headers": {- "Authorization": "Bearer <token>"- },- "enabled": true,+ "type": "stdio",+ "command": "ai-memory",+ "args": ["mcp-bridge", "--agent", "muse",+ "--server-url", "http://127.0.0.1:49374/mcp",+ "--data-dir", "/home/you/.local/share/ai-memory"],"mode": "optional"}}}```-Print or apply the configuration with:--```bash-ai-memory install-mcp --client muse-ai-memory install-mcp --client muse --apply \- --server-url "http://homelab:49374/mcp" \- --auth-token "$TOKEN"-```+Muse starts stdio servers with a cleared environment, so the entry names the+install's data dir and the bridge reads the server's token from there at+launch. A token passed explicitly with `--auth-token` is written to the+entry's `env` as `AI_MEMORY_AUTH_TOKEN`; treat the file as private then. The+bridge reads only `MUSE_SESSION_ID` when started with `--agent muse` (and only+`CLAUDE_CODE_SESSION_ID` for Claude Code), so an id inherited from another+harness's terminal is never forwarded, and it refuses to start without its+own id.-Two details of Muse's schema are worth knowing before hand-editing the file:+Three details of Muse's schema are worth knowing before hand-editing the file:- **`"schema_version": 1` is mandatory.** A settings file that omits it fails- *every* `muse` command at startup with `malformed settings file`. `--apply`+ every `muse` command at startup with `malformed settings file`. `--apply`adds the key when it is missing and never rewrites an existing value, so afuture schema is not silently downgraded.+- **`mcpServers` or `mcp_servers`, never both.** Muse reads servers from+ `mcpServers` (`"type": "stdio"`) or the legacy `mcp_servers`+ (`"transport": "stdio"`), and ignores every MCP server when both maps are+ present. `--apply` uses `mcp_servers` when the file already has it, else+ `mcpServers`, and refuses a file that already holds both;+ `ai-memory doctor` reports that state.- **`mode` defaults to `required`**, and a required server that fails to start- aborts the whole Muse run. ai-memory writes `"mode": "optional"` explicitly- so an unreachable memory server costs you recall rather than the session.+ aborts the whole Muse run. ai-memory writes `"mode": "optional"`, so an+ unreachable memory server only costs you recall and the session goes on.-A non-default `framing` value is rejected on `streamable_http`, so the-generated entry omits the key.+`install-hooks --agent muse` run without `--server-url` reads the URL back+from this entry. The hook installer and its events are described in+[`install.md`](install.md#meta-muse-code).**Skills:** no extra step is needed. Muse Code loads user skills from`$XDG_CONFIG_HOME/muse/skills` and `~/.agents/skills`, and@@ -565,12 +577,6 @@ generated entry omits the key.root, so the ai-memory routing skills are visible to Muse. Confirm with`muse skills list`.-Muse Code documents a lifecycle hook surface, but the output contract of its-`SessionStart` event is not specified, so automatic capture and automatic-handoff injection are not claimed here. Ask the agent to call-`memory_handoff_begin` before leaving and `memory_handoff_accept` when-resuming when you need continuity.-Sources: <https://dev.meta.ai/docs/muse-code/configuration>,<https://dev.meta.ai/docs/muse-code/extending>.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 18396304..074bc464 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -52,7 +52,7 @@ means the boundary is not built yet.| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks || 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI || 5e | Conditional page mutation (#986, invariant #16) | `ai-memory-store/src/ops.rs` `upsert_page_if` reads the latest version and writes in one transaction, the authority; `ai-memory-wiki/src/wiki.rs` `write_page_if` pre-checks under the per-page lock before touching disk and restores the file when the store check fails; conditional deletes reuse `delete_page_if_latest` (exclusive mutation lock plus an in-transaction check). `ai-memory-mcp/src/server.rs` checks the precondition only after scope resolution and the write grant, against the resolved scope's own latest row, and returns `precondition_failed` with no write, checkpoint or webhook dispatch | `multi_session.rs` `conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed` (two writers from one version: one wins, the base stays reachable, no loser row; fails with the store check removed); `server.rs` `conditional_page_writes::*` (stale id, `create_only` on an existing page, a version id from another project, and conditional deletes are refused and change nothing, with and without the wiki pre-check; the store check proven to bite with the reader pre-check off); `a_reader_may_read_everything_and_change_nothing` (a read-only user's conditional write or delete, with the right id or a wrong one, gets the authorization error and no version data; the page is unchanged) | STRONG |-| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one) and `a_session_less_upstream_config_carries_no_session_header` | STRONG |+| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer; the session-aware bridge reads only the variable its `--agent` names (`CLAUDE_CODE_SESSION_ID`, or `MUSE_SESSION_ID` for Meta Muse Code), so neither harness's id stands in for the other's | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one), `each_harness_forwards_only_its_own_session_id` (a Muse bridge never forwards an inherited Claude id and fails closed without its own, a Claude bridge never forwards an inherited Muse id; controls forward each harness's own id) and `a_session_less_upstream_config_carries_no_session_header`; `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (the built `mcp-bridge --agent muse` refuses to start with only `CLAUDE_CODE_SESSION_ID` set) | STRONG || 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG || 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG || 7 | Sanitizer trust boundary (invariant #6) | `ai-memory-core/src/sanitize.rs` `Sanitized<T>` (private field, only `sanitize()` ctor); `Sanitized::new` scrubs the title *before* the 80-char display cap; `ai-memory-mcp/src/server.rs` `sanitize_feedback_reason` scrubs the reason *before* the 500-char cap; `ai-memory-hooks/src/router.rs` `durable_body` scrubs the full excerpt *before* the per-event body caps (`payload::durable_body_cap`), which no longer run at excerpt extraction; `ai-memory-hooks/src/payload.rs` `cap_object_fields` scrubs with the built-in sanitizer *before* the client spool cap; `WriterHandle::insert_observation` requires `Sanitized`; `ops` crate-private | Structural (compile-time) + `store/src/lib.rs` `insert_observation_boundary_scrubs_before_disk` + sanitizer scrub unit tests + `ai-memory-core::sanitize` `title_is_scrubbed_before_the_80_char_cap_runs` + `ai-memory-hooks::router` `issue_980_user_prompt_title_is_sanitized_before_truncated` (a secret straddling the 80-char boundary is redacted, not stored truncated; #980) + `ai-memory-mcp::server` `feedback_reason_is_scrubbed_before_the_500_char_cap` (#1109) + `ai-memory-hooks::router` `issue_1114_user_prompt_body_is_sanitized_before_the_16kib_cap`, `issue_1114_post_compaction_body_is_sanitized_before_the_16kib_cap`, `issue_1114_tool_body_is_sanitized_before_the_2kb_cap`, `tool_body_cap_keeps_the_utf8_boundary` + `ai-memory-hooks::payload` `client_body_cap_scrubs_before_truncating` (each places a secret straddling the cap and asserts a `[REDACTED:…]` marker survives with no raw fragment; #1114) | STRONG (structural) |@@ -76,7 +76,7 @@ means the boundary is not built yet.| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG || 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized, and every word that holds several words, such as a quoted `sh -c` script or a `"$(…)"` substitution, re-split to four levels by `ShellCommand::split`/`push_nested_words`, a deeper script metadata-only; ANSI-C strings decoded and a backslash before an ordinary letter dropped (`shell_words`, `push_word`); backslash-newline continuations joined (`shell_words`); a parameter default's operand, a value glued to a short flag and a `file:` URL's path read as candidates (`parameter_operands`, `shell_arguments`, `file_url_path`); PowerShell and cmd escape characters read out under the `PowerShell` tool or on a Windows host (`without_windows_escapes`); `~+` resolved to the cwd and a `~-`/`~N`/`~name` prefix metadata-only (`names_unknown_directory`); shell and interpreter options that take a value skipped while looking for a `-c` script or inline code (`takes_shell_value`, `runs_inline_code`, which also lists `lua`/`Rscript`/`osascript -e`, and `su -c`/`script -c` as script runners); paths compared without regard to case on a macOS host (`fold_case`, set by `resolve`; patterns and candidates composed to NFC and lowercased in full by `fold_path`, TS `captureFold`; client-only, the server's sentinel re-inspection never depends on it); a `file:` URL cut at its query or fragment before decoding (`file_url_path`); a parameter default nested past four levels metadata-only and a default read again after backslash removal (`parameter_operands`, `push_word_reading`); a tilde expanded or treated as an unknown directory only when the shell expands it, unquoted and in a script rather than a quoted message or argv element, every tilde under PowerShell (`marked_shell_words`, `literal_tildes`, `expand_tilde`); a file or shell read of a harness's saved tool output, or a glob that could match one, metadata-only under an active policy (`output_spool`: Claude Code `tool-results/` and `tasks/*.output`, OpenCode `tool-output/`, Pi `pi-bash-*.log`; glob segments fit a name they share a match with, `globs_intersect`, TS `captureGlobsIntersect`, and one fitting segment must spell three characters in a row of that name's distinctive text literally, `spells`, TS `captureSpells`, so `*.log` is not read as `pi-bash-*.log`, a trade-off that leaves a glob with no such literal run, `/tmp/p?-b*`, outside the rule; the TS matcher applies it to `read_many_files` entries too); every other marker governing a file-tool target (an `apply_patch`'s header paths, read after leading whitespace, `patch_paths`), a search/list tool's directory, file or path-like glob argument (`search_scope`, Hermes `file_glob` included; a grep `pattern` is not read) or a separator-bearing shell argument also inspects the call, found by the lexical marker walk from each location's nearest existing directory, each directory's answer remembered for every lookup that passes it (`marker.rs` `MarkerMemo`, TS `captureMemoMarker`, seeded with the event's own walk, `remember`, TS `captureMemoRemember`), bounded (4,096 locations, 16 markers, and 16,384 probes sharing the glob walk's 50 ms, `MAX_LOOKUP_PROBES`, TS `CAPTURE_MAX_LOOKUP_PROBES`; locations outside the own checkout are looked up first, a glob's literal root before the walk below it (whose single listing can spend the time budget on a large directory), and past a bound fail closed as under an invalid policy, while running out inside the own checkout, whose locations are looked up shallowest first, ends the lookup, its own policy governing there) and combined strictest-first (`capture_lookup_locations`, `CaptureDecision::stricter`, `hook.rs` `foreign_capture_decision`, also applied by `transcript_capture.rs` `decide_call`; TS `captureForeignConfigs`, `captureDecide`, `captureSearchScope`, `capturePatchPaths`); a location with glob syntax is looked up from its literal root and, when that root lies outside the event's `.git` checkout, every directory the glob could pass through is checked for a marker (`glob_walk`, `hook.rs` `GlobBudget::markers_below`; TS `captureGlobWalk`, `captureMarkersBelow`, `captureOwnCheckout`: a `*`/`?` segment lists the child directories it matches, a class/brace/group every child, a `**` the subtree except the event's checkout's; a glob rooted inside the event's checkout is not walked; a checkout root at or above the home directory, or the filesystem root, is never the own checkout for these rules (`own_checkout`), so a dotfiles `~/.git` does not stop the walk from `~/Projects`; symlinks never followed; 256 directories, counted as a `**` lists, 32,768 entries and 50 ms, `MAX_GLOB_TIME`, TS `CAPTURE_MAX_GLOB_MS`, injectable clock, past which, or for a brace/group spanning a separator, a `..`/`~` alternative or one a bounded brace expansion builds, `brace_alternatives`, TS `captureBraceAlternatives`, a directory alternative bash before 5.2 expands to `..` (`.{*,x}/`), or an expansion too large to list whose pieces could build one of these (`brace_overflow_could_leave`, TS `captureBraceOverflowLeaves`: integer and letter sequences cannot, so `file{1..200}.txt` is walked like any glob), the call fails closed); a `..` after a `**` is read both as the `**` matching no directory and as matching some, by the event's own matcher and the lookup (`normalize_readings`, TS `captureReadings`, at most 16 readings, past which the call fails closed), and so is a directory segment that bash before 5.2 can expand to `..` (`could_name_parent`, `class_glob_matches` with POSIX classes such as `[[:punct:]]` and extglob groups such as `@(.)`, `?(.)`, `*(.)`, `+(.)`, `!(x)`; TS `captureCouldNameParent`, `captureClassGlob`, `captureNamedClass`), read as `..` too; inside double quotes a backslash before `$` or a backquote is dropped, so a quoted script (`bash -c "…"`, `eval "…"`) re-split for its words reads an ANSI-C string as the shell it runs does (`shell_tokens`, TS `captureMarkedWords`); a zsh glob group kept in its word and ANSI-C numeric escapes decoded are fed to the lookup (`shell_tokens` with `expand`, `ShellWords::expanded`, `glob_group`, `ansi_c_numeric_escape`; TS `captureMarkedWords(…, true)`, `captureGlobGroup`, `captureAnsiNumeric`); a file tool whose targets cannot be read or resolved, and a search/list argument that is not a string, fail closed; the path of a git `REV:path` object name tried from the cwd and the marker directory (`git_object_path`); Antigravity `run_command` resolved from its `Cwd`); an invalid marker makes file, search/list and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion, a bracket class (a leading `]` included), a zsh glob group or extglob, or a numeric/control ANSI-C escape (`has_unevaluated_expansion`, also run on scripts given to `sh -c`, `eval` or a substitution), or when it runs inline interpreter code (`runs_inline_code`: `python -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); Factory Droid's Claude-shaped payload is read by `extract`, its `Create` and `ApplyPatch` are file tools for that agent only (`agent_family`), `ApplyPatch` reads its `input` envelope like Codex `apply_patch`, and its `LS` `directory_path`, `Glob` `folder`/`patterns` and `Grep` `glob_pattern` locate the call for the cross-checkout lookup (`search_direct_paths`, `search_scope`) (#1240); Meta Muse Code's Claude-shaped payload is read by `extract` with its `tool_use_id`, its `read_file`/`write_file`/`edit_file` `path` resolves lexically against `cwd`, its `read_memory`/`add_memory`/`edit_memory` are file tools for that agent only whose `project`-scope `path` is placed under `.agents/memory/` and whose personal scopes fail closed to metadata-only (`muse_memory_paths`), `monitor` is a shell for that agent only, and `bash_input` is an output reader for that agent only; generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureShellSplit`, `captureUnevaluatedExpansion`, `captureInlineCode`, `captureGitObjectPath`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, the `ai-memory run` ledger upload, and `ai-memory recover`'s finish-failed re-import and degraded-run replay in `recovery.rs` `recover_finish_failed`/`recover_degraded_run`, each built for the journaled checkout's `cwd`) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn when the result has no id; a result whose id matches no call, or with no call, follows the orphan rule: dropped under a policy, content-free without one), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder keeping only the family and a call id that passes the server's `valid_call_id` (ledger), and a shell call whose recorded arguments cannot be parsed drops; both imports also apply the hook's repository admission gate (`hook.rs` `checkout_admits_capture`: persisted capture mode, marker opt-in, readable routing marker — the same helpers the hook's own gate uses), so under allowlist mode an unmarked checkout imports nothing, prompts included: `backfill` stops before contacting the server and the run ledger finishes with no events; a tool the transcript names differently from the hook is rebuilt under the hook's name and fields (`capture_policy.rs` `hook_tool_call`: Codex `exec_command` `{cmd, workdir}` → `Bash` `{command, workdir}`); the Claude Code and Codex JSONL adapters label each event with its record's cwd (`transcript.rs` `stamp_record_cwd`, `RECORD_CWD_KEY`), from which the import resolves arguments, policy and reroutes, falling back to the session cwd, and which is removed before a ledger upload; a rerouted call, and an event whose record cwd lies outside the checkout, must pass that directory's admission gate, resolve to the same server-profile route as the checkout and to the same project scope (`transcript_capture.rs` `admits_elsewhere` → `hook.rs` `checkout_admits_capture` + `delivers_to_same_server`, which compares two `resolve_hook_route` results and never matches a refused selection, + `routes_to_same_project`, which compares the two `hook_scope` hint sets and, when they leave the project to the server, under `repo-root` the repository/marker anchor or the directory itself, under the default `basename` the directory itself or a destination inside the repository whose root is the source), else it drops with its result, since the import files every event under the importing project; compaction, checkpoint and annotation events answer to the same record-cwd checks; Claude Code `!` shell-mode output (a user message opening with a `<bash-stdout>`/`<bash-stderr>`/`<local-command-stdout>` block, whatever it holds) is dropped (`shell_mode_output`); the Claude Code adapter excludes harness-written background-task turns (`transcript.rs` `claude_task_notification`: `origin.kind` `task-notification` in any case, or a first text block opening with a `<task-notification` tag in any case, attributes allowed, after a byte-order mark, zero-width characters or whitespace) and records a compaction summary (`isCompactSummary` true, `"true"` or `1`, `truthy`) as a compaction event, which backfill does not post; a tool the matcher does not recognize (unknown family: MCP tools, Codex `view_image`, …) keeps only its family whatever the policy, as the live server stores for it (`EventCapture::Unrecognized`: backfill posts title `tool unknown` and body `tool_family: unknown`, the ledger a withheld placeholder), and so does a result with no call to inherit from ; in a Windows session every candidate, shell argument and `workdir` is read as the file Windows opens before matching (`windows_spelling`, `windows_segment`, `command_base`; TS `captureWindowsSpelling`/`captureResolve`/`captureBase`): Git Bash/MSYS2/Cygwin `/c/…` and `/cygdrive/c/…`, a drive-less rooted path on the cwd's drive, the `\\?\`/`\\.\`/`\??\` and `UNC` prefixes, the local administrative share (`\\localhost\C$`), and per-segment alternate-data-stream suffixes and trailing dots/spaces, any other device path unusable (metadata-only for a file tool); `/c/…` and `/cygdrive/c/…` are also read from the root of the cwd's drive, as a native tool reads them, and either reading matching drops (`windows_spellings`, `normalize_candidates`, `normalize_readings`; TS `captureWindowsSpellings`/`captureAllReadings`); the cwd, the marker directory, home and an absolute pattern get the same reading so every side shares one spelling (`normalize_root`, `compile`; TS `captureRoot`, the marker directory cut lexically); a Windows session also reads each shell command and argv element with every backslash literal, as PowerShell and cmd do, so a bare or double-quoted `\\server\share\…` or `\\?\C:\…` argument keeps its prefix (`literal_shell_words`, threaded through `push_nested_words`/`push_argv_item`; TS `captureMarkedWords(…, literal)`); the harness-spool check is linear in the path and charged to the match budget, past it fail-closed (`output_spool`, TS `captureOutputSpool`); a shell command over `MAX_SHELL_COMMAND_CHARS` (1 MiB) is metadata-only and its marker lookup unprovable (`ShellCommand::oversized`, TS `captureCommandOversized`); Hermes `execute_code` is metadata-only under an active policy (`INLINE_CODE_TOOL_NAMES`); the TS file/search/non-file/inline-code/output-reader tool lists and the command limit are generated from the native constants (`FILE_TOOL_NAMES` and siblings, spliced by `ts_capture_policy_v1`), and the TS marker reader honours every TOML spelling of the capture table toml_edit does (dotted `capture.ignore_paths`, quoted or spaced `[capture]` headers) and fails closed on the shapes it rejects (inline table, `[[capture]]`, `[capture.x]`, a second definition) (`captureTomlKey` and the `captureConfigAt` section loop), tracks every multi-line array so a line inside one (`["docs"]`) is never a header, and fails closed on a line that is neither header nor key/value, a key line swallowed by an open array, text after a continued array closes, or an inline table left open at a line end (`captureValueScan`); the TS glob walk reads a directory one entry at a time with `opendirSync`, stopping at the entry bound; in a Windows session a shell argument or `workdir` that is drive-relative (`C:docs\x`, a bare `C:`) or a device path naming no drive or share (`\\?\GLOBALROOT\…`, `\\.\HarddiskVolume3\…`) makes the command metadata-only, a POSIX shell's reading of a placeable native path (`C:\repo\x` read as `C:repox`) excused and a device reading never (`windows_unplaceable`, `match_command`, the `workdir` check in `inspect`; TS `captureWindowsUnplaceable`, `captureMatchCommand`, `captureDecide`); a PowerShell `FileSystem::`/`Microsoft.PowerShell.Core\FileSystem::` provider prefix is dropped before a Windows path is read (`strip_powershell_provider` in `candidate_raw`/`command_base`; TS `captureStripProvider` in `captureResolve`/`captureBase`); a POSIX absolute pattern in a Windows marker makes the marker invalid (`compile`; TS `captureConfigAt`) (GHSA-gcpc-88hm-3xqr) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting` (also leading-`]` classes, zsh groups and extglobs, ANSI-C numeric escapes; subshells, `$((…))`, `<(…)`, array assignments kept), the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `quoted_scripts_in_string_commands_are_read_like_command_lines` (`sh -c`, `timeout … bash -c`, `"$(…)"`, `NAME="$(…)"`, backquotes, two nested shells and an inline-interpreter literal drop; `bash -c 'cargo test'` and `"$(git rev-parse HEAD)"` kept; four levels read, a fifth metadata-only), `inline_interpreter_code_is_metadata_only_under_an_active_policy` (inline code metadata-only, kept with no policy; modules, script files and `grep -e` unaffected), `git_object_names_are_path_candidates` (`HEAD:`, `:`, `:N:` and `@{n}` names drop, also from a subdirectory; drive letters, URLs, `NAME=a:b` and flags are not object names; a public object name kept), `ansi_c_strings_and_escaped_letters_are_read_like_the_shell`, `antigravity_run_command_resolves_arguments_from_its_cwd` (absolute and relative `Cwd` drop, a public `Cwd` kept, another agent's `Cwd` key ignored), `windows_escape_characters_are_read_on_a_windows_host` (caret and backquote spellings drop on a Windows host, public controls kept, a POSIX host reads both literally), `a_case_folding_host_matches_paths_without_regard_to_case` (file tool and shell drop with folding, keep without, public control kept; folding injected through `resolve_for_host` so it runs on every CI OS), the shell fixture's continuation, PowerShell/cmd escape, option-value, runner, interpreter, glued-flag, `file:` URL, tilde, parameter-default and `fold_case` vectors with their controls, the near-miss controls added to `common_commands_stay_kept_under_an_active_policy` (also quoted tildes, a `file:` URL with a query, a shallow nested default and a scratchpad log), the shell fixture's `file:` query/fragment, deep-default, escaped-default, quoted/argv/script tilde, PowerShell tilde, harness-output and Unicode `fold_case` vectors and the `decisions` harness-output vectors with their controls, `reading_a_harness_output_spool_is_metadata_only_under_a_policy` (active and invalid strip, inactive keeps, same-named files elsewhere kept, an ignored path still drops), `capture_lookup_locations_name_every_path_a_call_spells`, the Unicode rows of `a_case_folding_host_matches_paths_without_regard_to_case`, **`hook.rs` `another_checkouts_exclusions_hold_for_a_call_made_elsewhere`** (relative, absolute, glob and unmarked-Hermes shell calls naming another checkout's excluded file never spool; a broken foreign marker and too many foreign markers spool metadata-only; public, own-file and few-marker controls spool with content), **`hook.rs` `globs_searches_and_unreadable_targets_answer_to_another_checkout`** (sibling and parent-folder `*`, brace, bracket, `**` and separator-spanning-brace shell globs, a Grep path, a Glob pattern, a parent-folder Grep filter, a Gemini `search_file_content` directory, a Codex `apply_patch` header and a target-less Read never spool content; public-glob, own-glob, own-`**`, own-search, own-Glob-`**`, public-search and own-patch controls spool with content), `transcript_capture.rs` `globs_and_searches_reaching_another_checkout_honor_its_policy`, `capture_policy.rs` `glob_walk_follows_every_segment_a_glob_could_pass_through`, `an_invalid_policy_makes_a_search_metadata_only`, `a_brace_that_builds_a_parent_step_cannot_be_walked`, `a_parent_step_after_a_globstar_is_read_both_ways`, `glob_groups_and_ansi_c_escapes_reach_the_marker_lookup`, `a_saved_output_glob_needs_its_distinctive_name_in_literal_text`, `indented_patch_headers_and_hermes_file_globs_reach_the_marker_lookup`, `a_dot_glob_directory_that_can_match_the_parent_is_read_as_it` (POSIX classes and extglob groups included), `an_oversized_brace_expansion_is_walked_unless_its_pieces_could_leave` (each attack with its control), the shell fixture's double-quoted `bash -c`/`eval` ANSI-C vectors and their controls, `marker.rs` `marker_memo_answers_like_find_marker_once_per_directory`, **`hook.rs` `a_globstar_above_the_checkout_skips_the_own_subtree`** (regression: `ls ../**/README.md` from a 300-directory checkout with no policy is not metadata-only; the sibling `cat ../**/secrets.env` drops), **`hook.rs` `marker_lookups_in_a_deep_tree_cost_one_probe_per_directory`** (regression: 300 paths in a 300-level tree cost fewer than five probes per level; out of budget inside the checkout kept, outside it metadata-only, the sibling checkout's location looked up before a long list inside the checkout, and a shallow nested marker before a deep list), **`hook.rs` `a_dotfiles_checkout_at_home_is_not_the_own_checkout`** (with `~/.git`, `cat */secrets.env` from `~/Projects` drops; a harmless glob kept), the shell fixture's dot-glob directory vectors and their controls, the shell fixture's `**`-then-`..` and `*.log` vectors and the `read_many_files_directories` `**`-then-`..` vectors, **`hook.rs` `constructed_parent_steps_answer_to_another_checkout`** (a `..` after a `**` through a shell, a Glob pattern and a Grep filter, four brace expansions that build a parent step, two zsh glob groups, hex and octal ANSI-C escapes, two dot-glob directory segments, a POSIX-class and four extglob dot-glob segments, a brace-built dot-glob, an oversized brace sequence over `.`, ANSI-C strings in a double-quoted `bash -c` and `eval`, an indented `apply_patch` header next to an unindented one and a Hermes `file_glob` never spool content; the same shapes inside the checkout spool with it, and so do four brace expansions too large to list that cannot leave it, which v2.6.3 kept), **`hook.rs` `a_monorepo_glob_inside_the_own_checkout_is_not_walked`** (in a 300-package checkout, with and without a policy of its own, `packages/*` shell globs stay kept and the sibling `../*/secrets.env` and `../a/*.env` attacks still drop), `hook.rs` `a_glob_walk_outside_the_checkout_stops_at_its_bounds` (directory bound counted while a `**` lists, time budget through an injected clock, no walk inside the checkout), the Node evidence test's `monorepo-*`, `walk-*`, `con-*`, `globstar-*`, `deep-*` and `dotfiles-*` checks, and the Node evidence test's `glob-*`, `search-*`, `patch-*` and `unreadable-target` checks with their controls and `transcript_capture.rs` `a_shell_command_naming_another_checkouts_file_honors_its_policy`, both failing with the foreign lookup disabled, and the Node evidence test's `cross-*` and `fold-unicode` checks, which fail with `captureForeignConfigs` disabled, and the shell fixture's quoted-script, git-object, ANSI-C, escaped-letter and inline-interpreter vectors with their controls (`cargo test`, `git status`/`log`, `pytest`, `python3 -m pytest`, `node build.js`, `npm run test`, a quoted commit message with braces); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `capture_policy.rs` `droid_tool_calls_honor_capture_exclusions` (`Read`/`Create`/`Edit` naming an ignored path drop and a control path keeps, `ApplyPatch` is metadata-only like Codex `apply_patch` and its headers name the lookup location, `LS`/`Grep`/`Glob` drop and their directory and glob arguments locate the call, `Execute` naming an ignored path drops; every excluded case keeps under `AgentKind::Other`, so it fails with the Droid `extract` arm or the `Create`/`ApplyPatch` mapping removed) and the `droid` `decisions` fixture vectors (#1240); `capture_policy.rs` `muse_tool_calls_honor_capture_exclusions` (`read_file`/`write_file`/`edit_file` naming an ignored path, relative or absolute, and the project-scope memory tools naming an ignored `.agents/memory` path drop while a control path keeps, personal-scope memory calls are metadata-only, `apply_patch` is metadata-only like Codex's, `search` drops, `bash`/`monitor` naming an ignored path from their `workdir` drop, `bash_input` is metadata-only; each excluded case keeps under `AgentKind::Other`, so it fails with the Muse `extract` arm removed), `muse_tool_payload_fields_carry_the_call_id` and the `muse` `decisions` fixture vectors, taken from Muse Code 1.4.7 hook payloads; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; **`recovery.rs` `finish_failed_recovery_never_posts_content_the_capture_policy_excludes`** and **`degraded_run_recovery_never_posts_content_the_capture_policy_excludes`** (a full `recover` pass over a journaled Claude transcript with exact digests and cursor, marker `ignore_paths = ["secrets/**"]`: the excluded read's path and `SENTINEL_RECOVERY_MUST_NOT_POST` output never reach `/workstream/runs/{id}/recover` or `/hook/batch`, the public read's output does; each fails when its own call site's capture is built for `/` instead of the entry's `cwd`, on the control since a foreign-scoped capture fails closed, and both fail on the sentinel when `for_checkout` loses the marker's policy); `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent`; **`backfill.rs` `allowlist_mode_backfills_nothing_from_an_unmarked_checkout`** (no request reaches the server; marked-checkout and denylist controls do), **`run.rs` `ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout`** (finish carries no prompt or tool content; marked and denylist controls upload both), `transcript_capture.rs` `allowlist_mode_admits_nothing_from_an_unmarked_checkout`, all failing with the admission gate removed; **`backfill.rs` `backfill_inspects_codex_exec_command_as_the_hook_shell_call`** and **`run.rs` `ledger_upload_inspects_codex_exec_command_as_the_hook_shell_call`** (a planted Codex `exec_command` whose `workdir`-relative argument names an ignored file never posts its call or output; the same command from a public `workdir` does), `capture_policy.rs` `codex_transcript_exec_command_is_inspected_as_the_hook_bash_call` (absolute, relative and absent `workdir` and an argv `cmd` drop, public control kept, the `workdir` locates the call, another agent's `exec_command` stays unknown), all failing with `hook_tool_call` removed; **`backfill.rs` `backfill_resolves_each_call_from_its_record_cwd`** (`cat adr/x.md` recorded from `docs/` never posts; the same command from the root does) and `transcript.rs` `jsonl_events_carry_their_record_cwd` (Claude per line, Codex per turn context, a relative cwd ignored), failing with the record cwd ignored or unstamped; **`backfill.rs` `backfill_drops_reroutes_the_live_hook_would_not_deliver_here`** (under allowlist mode, reads rerouted to an unmarked git repository, to a marker selecting an unregistered profile, and to a marker selecting a registered profile while the source uses the install default are never posted; a read in a marked checkout with no server selection is the posted control), failing with either the admission check or the route comparison removed (each refused case checked on its own); `transcript_capture.rs` `a_record_cwd_answers_to_the_hook_admission_gate_there` (prompt, call and result recorded in an unmarked repository drop under allowlist; a subdirectory of the opted-in checkout is kept and its record cwd never reaches the ledger) and `claude_shell_mode_output_is_not_imported` (stdout, stderr, local-command and size-capped blocks drop; `<bash-input>`, a prompt quoting a tag, and another agent's message kept); **`backfill.rs` `backfill_posts_no_content_for_unrecognized_tools`** (a planted Codex MCP call's arguments and output never post, the call and output post as `tool unknown`; a recognized shell output is the posted control) and `transcript_capture.rs` `unrecognized_tools_keep_no_content_with_or_without_a_policy` (no policy and an active one; ledger content withheld; public read kept; a call-less result content-free), failing with the unknown-family rule removed, the backfill one also with its content-free body removed; **`backfill.rs` `backfill_keeps_reroutes_to_the_same_server_profile_only`** (a reroute into a checkout selecting the source's registered profile and project is posted; one selecting a different registered profile is not, nor one of another project on the same profile, nor a prompt recorded there), failing with the profile comparison forced either way and with the project comparison removed; `transcript_capture.rs` `a_record_cwd_in_another_project_is_dropped` and `a_reroute_into_another_project_is_dropped` (prompt, call and result recorded in, or a read reaching into, a checkout declaring another project drop; one declaring the same project is kept), failing with `routes_to_same_project` removed; `hook.rs` `subdirectories_of_one_repository_are_one_project_only_under_repo_root` (two subdirectories of an unmarked repository, and a subdirectory importing its root, are two projects; the same directory, the root importing a subdirectory and a `repo-root` marker agree), failing with the basename rule removed; **`backfill.rs` `backfill_posts_no_task_notification_or_compact_summary_as_a_prompt`** and `transcript.rs` `claude_adapter_keeps_task_notifications_and_compact_summaries_out_of_prompts` (a monitored command's notification, a background agent's report and an origin-tagged notice are excluded, also behind a byte-order mark and zero-width characters, in another case, with attributes, after a non-text block, or with an origin kind in another case; a compact summary, also flagged `"true"` or `1`, becomes a compaction event; the typed prompt, also one quoting the tag, and a look-alike tag are the controls), failing with either adapter rule removed or with the spelling rules reverted; `transcript_capture.rs` `boundary_events_answer_to_the_record_cwd_admission_gate` (compaction and annotation recorded in a refused directory drop; in the checkout kept), `a_result_whose_id_matches_no_call_is_an_orphan` (an unmatched id cannot borrow a public read's keep; the read's own result kept), `claude_shell_mode_output_is_not_imported` (a block holding a literal closing tag drops) and `unrecognized_tools_keep_no_content_with_or_without_a_policy` (ledger keeps no tool name and no invalid call id), each failing with its rule reverted; `windows_spelling_fixture_vectors` (shared `capture-policy.json` `windows` drop vectors for every spelling above, file tool and shell, with other-drive, other-share, longer-name and pipe controls, and `windows_posix_controls` proving a POSIX session keeps `/c/…`, trailing-dot and colon names; `windows_scopes` drop vectors for a `\\?\C:\`, `\\?\UNC\…`, `\\localhost\C$\…` or UNC cwd and marker directory with relative patterns, a `\\?\C:\…` absolute pattern from `C:\repo`, bare and double-quoted `\\server\share\…`/`\\?\…`/`\\.\…`/`\\localhost\c$\…` PowerShell, cmd, `run_shell_command` and argv commands, and both readings of `/a/x` from `D:\a\…`, each with public-path, other-drive and other-share keep controls; the Node runtime evidence runs the same vectors with the marker spelled in the Windows cwd), `tool_family_fixture_vectors` (shared `tool_families`, every native name per family), new `decisions` vectors (`execute_code` metadata-only, `read_file`/`patch`/`fs_read` operations drop, `write_to_file`/`browser_navigate` keep), `output_spool_work_is_linear_and_budgeted` (a 2,040-wildcard-segment path stays under a linear work bound; 32 such paths fail closed; one long or 32 short paths keep), `an_oversized_shell_command_is_unprovable` (one character over the limit is metadata-only and unlooked-up, at the limit keeps, argv summed, inactive untouched), `inline_code_tools_are_unprovable_under_a_policy`, `hook_capture::capture_section_spellings_match_toml_semantics` (shared `marker_spellings`, including a nested-array line `["docs"]` before a dotted `capture.ignore_paths` that must still drop, and a key line inside an open array, text after a closed array and a multi-line inline table that must fail closed), and the Node evidence test running all of these vectors against the generated TypeScript plus its entry-bound read count for the directory walk; each fails with its rule reverted (Windows reading off, spool memo dropped or budget failing open, length check off, inline-code rule off, a name dropped from the list, TS dotted key or inline-table rule reverted, TS walk back on `readdirSync`, Windows reading of the cwd/marker directory or of an absolute pattern off, literal-backslash reading off, the cwd-drive reading of `/a/x` off, TS array tracking or any `captureValueScan` refusal off, Rust and TS alike); new `windows_scopes` vectors (drive-relative, device-namespace and Git Bash doubled-backslash shell words and a `C:docs` `workdir` metadata-only, `FileSystem::` file paths, shell words and `workdir` dropping, a POSIX absolute pattern in a Windows marker failing closed, with `type README.md`, `dir /s /q`, `git status`, a URL, `type C:\repo\README.md` and `Get-Content -Path C:\repo\README.md` kept) and `windows_marker_rejects_posix_absolute_patterns` (the same pattern stays active in a POSIX marker) fail natively and in the Node evidence test with the unplaceable check, its device branch, the `workdir` check, the provider strip or the marker rejection removed; removing the POSIX-reading excusal makes `type C:\repo\README.md` metadata-only, and excusing a device reading keeps the doubled-backslash device path; `capture_policy.rs` `windows_lookup_locations_keep_glob_segments_whole` (a Windows session trims trailing dots from plain segments only, so `{.,}.` still reaches `..` and the sibling checkout's marker; bites with the glob-segment exemption removed) | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and the output of a command substitution, a `cd` inside the command, a script read from a file or a heredoc fed to an interpreter (read only for the words it spells out), git's repository root approximated by the marker directory, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, a search tool rooted at a literal directory above another checkout (it is not walked) and a glob whose literal root lies inside the event's own checkout reaching a checkout nested there (it is not walked), a marker nested inside the own checkout below what the lookup budget reaches, a `.git` the same command creates (`touch .git; cat */x`: the hook reads the tree after the command ran, so that directory counts as the own checkout; a `.git` at or above the home directory never does), a parameter expansion next to glob syntax (`${X}/*/x`, not walked), a glob through a symlinked directory, a tool's own directory option (`git -C`), script runners and interpreters the matcher does not list (their words are still read, but expansion or inline code in them is not recognized), a value glued after the first letter of a short-flag cluster, non-ASCII percent-escapes in a `file:` URL, a bare word naming another checkout's directory (only separator-bearing arguments are looked up for another marker), harness output files outside the listed default locations, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, adapters that record no per-record cwd (Pi, OMP, OpenCode, Crush, Kimi Code, Command Code, Kiro, Grok) judge every event from the session cwd, a Codex ledger upload resumed from a mid-file cursor judges the events before the next turn context from the session cwd, and id-less adapters over-drop a whole turn's results when one call is excluded, and when the routing hints leave the project to the server, events from inside one repository count as the importing project even where the server has a separate project registered for a subdirectory (anywhere under `repo-root`; under `basename` only when the import runs from the repository root); a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Under allowlist mode a refused checkout's `ai-memory run` still records repository checkpoint metadata (HEAD, branch, a status hash and changed-path names, never file content), which the run also sends at launch. Re-splitting quoted words over-drops a quoted message naming an ignored path, and inline interpreter code is metadata-only under an active policy. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects. Bite checks: removing the nested re-split, the git object path or its marker-root base, Antigravity's `Cwd` key, the leading-`]` rule, either zsh-group rule, ANSI-C decoding or its numeric-escape rule, the `\o` reading, the inline-code rule, the nesting-depth rule, the nested-script scan, the line-continuation join, the Windows escape reading, the shell-option and interpreter-option value skips, the added runners and interpreters, the glued-flag value, the `file:` URL path, the `~+` resolution, the unknown-tilde rule, the parameter-default reading or case folding each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test; so does reverting the `file:` URL cut, the deep-default rule, the escaped-default reading, the quoted-tilde rule, the harness-output rule or Unicode folding (the new fixture vectors fail against the previous matchers in both languages), and disabling the foreign-marker lookup fails the native, import and Node cross-checkout tests; reading every glob location as literal, skipping search/list locations, or skipping a file tool whose targets cannot be read each fails the native, import and Node glob/search/unreadable tests, removing `apply_patch` header reading fails the own-patch control, and reverting the saved-output glob rule fails the new fixture vectors in both languages; walking globs rooted inside the event's checkout fails the monorepo tests, accepting any literal text for a saved-output glob fails the `*.log` vectors, removing the time budget or counting a `**`'s directories only after it lists fails the bounds tests, and removing the `**`-then-`..` readings, the brace-expansion check, the expanded lookup words, the patch-header trim, the `file_glob` key or the dot-glob parent reading each fails the Rust tests and the Node evidence test; treating every oversized brace expansion as leaving, dropping the brace-built dot-glob check, listing the own checkout's subtree under a `**`, looking up locations in their given order (outside before inside, then shallowest first), dropping the per-directory memo, counting a checkout at home as the own one, keeping the backslash before `$` in double quotes, or dropping the POSIX-class or extglob reading each fails its Rust test and the Node evidence test; in a Windows session a shell `workdir` spelled `/c/x` is read only as Git Bash reads it, so arguments resolved from it miss a native tool's `D:\c\x` reading, the TS marker reader rejects structural errors anywhere in the marker but does not validate other values' TOML (`x = nope` invalidates the policy only natively), an administrative share reached through a loopback or host alias other than `localhost`/`127.0.0.1` (`\\127.0.0.2\c$`, `\\127.1\c$`, `\\<hostname>\c$`) or a `\\wsl$\…` path is matched as the UNC path it spells, Windows matching folds ASCII case only, and a drive-relative word counts as placed when a placeable argument's POSIX reading spells it; a `**/` matches one or more directories, never zero (documented in `marker-file.md`) || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |-| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL; once `[auth].bearer_token_file` names `auth-tokens/default` (this install's root bearer), `commands/server.rs` `refuse_the_root_token_name` refuses `server add default` and `server remove default` so no profile can be handed, overwrite or delete the root bearer | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does); `server.rs` `the_root_bearer_file_name_cannot_be_registered_or_removed` (refused at the root bearer path; another name and an install without a root bearer file are the controls); `server_profiles.rs` `a_default_profile_shares_the_root_bearer_only_at_its_path`, `clear_tokens_keeps_the_root_bearer_and_removes_profile_tokens` | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |+| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL; once `[auth].bearer_token_file` names `auth-tokens/default` (this install's root bearer), `commands/server.rs` `refuse_the_root_token_name` refuses `server add default` and `server remove default` so no profile can be handed, overwrite or delete the root bearer | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `muse_hooks_honour_marker_scope_profiles_exclusions_and_allowlist` (the Meta Muse Code settings-hook front door: marker workspace/project, the profile's server and token never the install's, the payload's session id, an ignored relative `read_file` dropped with a kept control, allowlist silence from an unmarked checkout with a denylist control), `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does); `server.rs` `the_root_bearer_file_name_cannot_be_registered_or_removed` (refused at the root bearer path; another name and an install without a root bearer file are the controls); `server_profiles.rs` `a_default_profile_shares_the_root_bearer_only_at_its_path`, `clear_tokens_keeps_the_root_bearer_and_removes_profile_tokens` | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` || 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG || 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI || 11g | Cross-project tool attribution cannot bypass source or destination capture, or destination server routing (#932, #1199) | `ai-memory-hooks/src/capture_policy.rs` `absolute_tool_location_paths` accepts only bounded, recognized, absolute locations: file-tool targets, a search/list tool's explicit `path`, or a shell command's structured `workdir` (command text is never parsed for a location); `ai-memory-cli/src/commands/hook.rs` `tool_location_routing_cwd` requires every path to prove the same repository/marker boundary, refuses the reroute when the payload cwd's own capture policy would not keep the event (source `ignore_paths` may name paths outside the source checkout, and a command may name source files while its `workdir` points elsewhere), and resolves that destination before capture policy, allowlist marker, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths`, `workdir_reroute_applies_the_destination_capture_policy` (a `workdir`-rerouted command reading a destination-excluded path is dropped, public control kept), **`a_reroute_cannot_escape_the_source_capture_exclusions`** (adversarial: a file read under a source pattern that names another project's directory, and a shell command naming an excluded source file with `workdir` in another project, are both refused; public file and shell controls still reroute; fails with the source-policy check removed), `hermes_tool_location_finds_the_marker_the_process_cwd_lacks` (Hermes `terminal` `workdir`, `read_file` `path` and `search_files` `path` reach the repository marker under allowlist; no-workdir, relative-workdir and relative-search controls stay with the unmarked process cwd); `capture_policy.rs` `absolute_tool_location_paths_cover_search_dirs_and_shell_workdirs` (relative workdir, command-text paths, workdir without a command, and Hermes `process` yield no location) | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |@@ -84,7 +84,7 @@ means the boundary is not built yet.| 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; `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; 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 tool drop list (#1241) | `ai-memory-hooks/src/drop_list.rs` `IngestDropList::matches`, checked in `router.rs` `admit_hook` and the `handle_hook_batch` loop right after the client capture protocol and before the rate limiter, the ingest semaphore, the sanitizer and storage; lists from `[ingest] drop_tool_use_id_prefixes` / `drop_tool_names`, validated once in `Config::load` (at most 64 entries of 128 printable characters each). Only tool events match: a tool-call id by prefix, a tool name exactly, both read through the per-agent mapping `capture_policy::tool_payload_fields` that tool metadata uses (generic Claude-style fields for an agent without one; Factory Droid sends no tool-call id, so only its tool name can match; Meta Muse Code sends its provider call id in `tool_use_id`, so both can). A drop answers 202 and counts as `dropped_by_policy`; the matched value is never logged | `router.rs` `the_ingest_drop_list_drops_before_any_capacity_is_spent` (with the semaphore exhausted a listed event still answers 202; control: an unlisted one gets 429) and `the_ingest_drop_list_applies_to_hook_batches` (listed items acknowledged as policy drops, the unlisted item ingested); `drop_list.rs` unit tests (prefix only at the start, names only exact, non-tool events never match, bounds refused; `each_agent_is_matched_on_its_own_tool_fields` matches OpenCode `callID`, Hermes `extra.tool_call_id` and Antigravity `toolCall.name`, with same-agent controls kept, and fails when only the generic fields are read). Both router tests fail with `matches` forced to `false` | 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`); 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), `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`); 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`) || 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; `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; `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, `default` profile, env token); `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); `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 `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 || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op |diff --git a/docs/security.md b/docs/security.mdindex 7e64bd1e..634575dd 100644--- a/docs/security.md+++ b/docs/security.md@@ -8,7 +8,7 @@ only) and records `[auth].bearer_token_file`; the server then refuses everyroute except `/healthz` without it. The hooks, the CLI and the`ai-memory mcp-bridge` stdio bridge read it from the data dir, so the token isnever pasted into a harness config or passed on a command line. Claude Code-runs the session-aware bridge, Codex, Prime Agent and Factory Droid reference+and Meta Muse Code run the session-aware bridge, Codex, Prime Agent and Factory Droid referencethe token as `$AI_MEMORY_AUTH_TOKEN`, and every other MCP client `install-mcp` supportsruns `ai-memory mcp-bridge --no-session-id` as a local stdio server. ZCode,which takes only HTTP entries, is the exception and needs a manual entry.diff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 306cc8a2..5da4f7a9 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -43,7 +43,7 @@| 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. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. |-| Muse Code | MCP-only | `install-mcp --client muse` merges a native streamable-HTTP entry with bearer `headers` (a token-file install gets a stdio `ai-memory mcp-bridge --no-session-id` entry instead) into the snake_case `mcp_servers` map of `~/.config/muse/settings.json`, preserving sibling servers. The writer adds the mandatory `"schema_version": 1` when absent (without it every `muse` command fails at startup) and never rewrites an existing value, and it sets `"mode": "optional"` because Muse's default `required` aborts the whole run when the server is unreachable. Skills need no extra step: Muse reads `~/.agents/skills`, which `install-skills` already writes. Lifecycle capture and managed workstreams are not claimed — Muse documents a hook surface, but the output contract of its `SessionStart` event is not specified. |+| 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). || DeepSeek Harness (DSH) | MCP-only | `install-mcp --client dsh` prints a Cordis patch fragment (a `- insert:` item for `@deepseek-ai/dsh-mcp-client`) to merge into `$DSH_HOME/profiles/<profile>/cordis.patch.yml`; DSH has no fixed MCP config file, so `--apply` is refused. Lifecycle capture is not claimed: DSH's `@deepseek-ai/dsh-hooks-claude-code` bridge can run a Claude Code hook config, but ai-memory's Claude Code hooks would report DSH sessions as `agent=claude-code`, and the bridge delivers only seven Claude Code events (`PreCompact` and `SessionEnd` are not), with a detached `SessionStart`. No managed workstream. || Prime Agent | MCP-only | `install-mcp --client prime-agent` merges an HTTP entry (`type: "http"` + `url`) into the `mcpServers` map of `$PRIME_AGENT_CODING_AGENT_DIR/settings.json` (default `~/.prime/agent/settings.json`), preserving other settings and servers; a project's `.prime/agent/settings.json` works through `--config-file`. A token is referenced as `"bearerTokenEnvVar": "AI_MEMORY_AUTH_TOKEN"`, never written: Prime Agent 0.10 counts a user HTTP server as connected and names it in the model's prompt only with that variable set or an OAuth grant. A credential-less entry is still callable through `mcp.call_tool("ai-memory", ...)` but is not listed. The model reaches MCP tools from its Python REPL (`await mcp.call_tool("ai-memory", "memory_query", {...})`), and Prime Agent sends no session id or cwd, so pass `workspace` and `project` on project-scoped calls. Lifecycle capture and managed workstreams are not claimed: Prime Agent 0.10 removed the TypeScript extensions its 0.9 releases had and has no hook surface. Verified against Prime Agent 0.10.0. || Hermes Agent | Supported | `install-hooks --agent hermes` (alias `hermes-agent`) prints a ready-to-paste `hooks:` block for `~/.hermes/config.yaml`. Hermes splits each configured `command` with `shlex.split` and runs it with no shell, passing the event JSON on stdin, so the entries invoke the native `ai-memory hook` command (exec form, like Zero and ZCode — no script bundle is staged); ai-memory never writes that YAML file, which is yours to edit and which Hermes itself gates behind its hook-acceptance prompt (`hooks_auto_accept`). Two tool events are wired, `pre_tool_call` → `pre-tool-use` and `post_tool_call` → `post-tool-use`; their `tool_name` / `tool_input` payload drives concrete session attribution, tool-family titles, and capture exclusions. Hermes reports its own process directory as `cwd`, so the native hook locates each event's `.ai-memory.toml` from the tool's absolute `workdir` (`terminal`) or `path` (file tools, `search_files`); a call with no absolute location stays with the process directory. Session lifecycle (recall, prompt capture, session-end, automatic handoff) is owned by the community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) memory provider, so no hook-driven `session-end` is installed and nothing is duplicated; review that plugin's compatibility matrix, install/uninstall scripts, and secret handling before enabling it. No first-party `install-mcp` client and no managed workstream are claimed yet, and because Hermes ignores session-start hook stdout a pending handoff is recovered through MCP (`memory_handoff_list` then `memory_handoff_accept`). |diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.mdindex 2f4cd2c0..542bc867 100644--- a/docs/upgrading-to-3.0.md+++ b/docs/upgrading-to-3.0.md@@ -46,9 +46,9 @@ For the full list of changes, see the 3.0.0 section of- A server on another host: upgrade it there as well. `ai-memory upgrade`on a client machine only refreshes the local client and hooks.2. Restart the server if the upgrade did not. On the first start it applies- migrations V77, V78 and V79 before it accepts traffic. V78 and V79 rebuild- the `sessions` and `users` tables, so the first start on a large store can- take longer than usual.+ migrations V77 to V80 before it accepts traffic. V78, V79 and V80 rebuild+ the `sessions` and `users` tables (V78 and V80 `sessions`, V79 `users`), so+ the first start on a large store can take longer than usual.3. Check the result:```bash