Skip to content

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

Rust

feat(cli): install-hooks and install-mcp for Factory Droid

AkitaOnRailsc1608395727a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1653ee0..179f7a1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -350,6 +350,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
hooks already resolve for the checkout, so accepting them keeps the memory
where it is. It writes only those two keys, needs an interactive terminal,
and never overwrites an existing marker. (#1227)
+- Added first-class Factory Droid CLI support. `install-mcp --client droid`
+ (alias `factory-droid`) merges an HTTP entry into `~/.factory/mcp.json`,
+ with the URL written literally and a bearer referenced as
+ `Bearer ${AI_MEMORY_AUTH_TOKEN}`: Droid expands variables in headers but
+ never in the URL.
+ `install-hooks --agent droid` merges native
+ `ai-memory hook --event … --agent droid` commands for seven events into
+ `~/.factory/hooks.json`, keeps your own entries, changes nothing on a
+ re-run, and refuses to create that file while `~/.factory/settings.json`
+ holds hooks, which Droid would then stop reading. Sessions are recorded as
+ agent `droid` (migration V78). The `SessionStart` hook delivers the pending
+ handoff, and Droid's own `SessionEnd` closes the session. Droid's `Read`,
+ `Create`, `Edit`, `ApplyPatch`, `LS`, `Grep`, `Glob` and `Execute` tools
+ map to the file, search and shell families, so `[capture] ignore_paths`
+ applies to them: verified against the Droid 0.240.0 tool schemas; no
+ tool-call id in Droid payloads. `setup-agent --agent droid` prints the
+ hook config and `uninstall` removes both entries. (#1240)
### Changed
- Changed scoped `/api/v1/search` (a single `workspace` + `project`, or
diff --git a/README.md b/README.md
index 508145cf..f2295328 100644
--- a/README.md
+++ b/README.md
@@ -139,6 +139,7 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).
| Kiro CLI | Supported |
| Pool | Hooks-only |
| GitHub Copilot CLI | Supported |
+| Factory Droid | Supported |
| VS Code Copilot | MCP-only |
| Zed | MCP-only |
| Muse Code | MCP-only |
@@ -343,7 +344,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 omp`,
+# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--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/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index a6bfac9d..966f56d7 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -2463,6 +2463,17 @@ pub enum AgentChoice {
/// work.
#[value(name = "copilot-cli")]
CopilotCli,
+ /// Factory Droid CLI (`droid`) — lifecycle hooks merged into
+ /// `~/.factory/hooks.json` (#1240). Droid sends Claude Code-shaped hook
+ /// payloads on stdin, so each entry runs ai-memory's native `hook`
+ /// command directly; there is no script bundle. Droid reads the `hooks`
+ /// key of `~/.factory/settings.json` only while `hooks.json` is absent,
+ /// so `--apply` refuses to create `hooks.json` over hooks still kept in
+ /// `settings.json`. SessionStart stdout
+ /// (`hookSpecificOutput.additionalContext`) carries the handoff, and
+ /// Droid's own `SessionEnd` closes the session.
+ #[value(alias = "factory-droid")]
+ Droid,
}
impl AgentChoice {
@@ -2494,6 +2505,7 @@ impl AgentChoice {
Self::Zcode => AgentKind::Zcode,
Self::Hermes => AgentKind::Hermes,
Self::CopilotCli => AgentKind::CopilotCli,
+ Self::Droid => AgentKind::Droid,
}
}
@@ -2512,7 +2524,8 @@ impl AgentChoice {
| Self::Openclaw
| Self::Zero
| Self::Zcode
- | Self::Hermes => None,
+ | Self::Hermes
+ | Self::Droid => None,
_ => Some(self.kind().as_str()),
}
}
@@ -2712,6 +2725,14 @@ pub enum McpClient {
/// mode client.
#[value(name = "copilot-cli")]
CopilotCli,
+ /// Factory Droid CLI — `~/.factory/mcp.json`, servers under the root
+ /// `mcpServers` map with `type: "http"` + `url` (#1240). Droid expands
+ /// `${VAR}` only in `headers`, never in `url`, so the URL is written
+ /// literally and a bearer is referenced as `${AI_MEMORY_AUTH_TOKEN}`,
+ /// which must be exported where droid runs. Pair with
+ /// `install-hooks --agent droid` for lifecycle capture.
+ #[value(alias = "factory-droid")]
+ Droid,
/// Swival CLI — project-scoped `.swival/mcp.json` using native HTTP.
/// This integration is MCP-only; Swival's lifecycle callback does not
/// expose a stable session identifier for reliable capture correlation.
@@ -4524,6 +4545,28 @@ mod tests {
}
}
+ #[test]
+ fn droid_install_hooks_and_install_mcp_parse_with_the_factory_alias() {
+ for alias in ["droid", "factory-droid"] {
+ 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::Droid);
+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Droid);
+ // Native commands only: there is no `hooks/droid` 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::Droid);
+ }
+ }
+
#[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/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 6781aae9..52d6a7b7 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -5675,6 +5675,59 @@ mod tests {
);
}
+ /// Droid documents SessionStart stdout as context and parses a JSON
+ /// stdout's `hookSpecificOutput.additionalContext`, so `--agent droid`
+ /// fetches the handoff and prints Claude Code's envelope (#1240).
+ #[tokio::test]
+ async fn droid_session_start_prints_hook_specific_handoff_envelope() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (base, mut requests) = serve_requests("200 OK", "DROID-HANDOFF").await;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(tmp.path().join("data")),
+ HookArgs {
+ agent: "droid".into(),
+ ..copilot_cli_hook_args("session-start", &base)
+ },
+ serde_json::json!({
+ "session_id": "droid-session",
+ "transcript_path": tmp.path().join("s.jsonl"),
+ "cwd": tmp.path(),
+ "permission_mode": "auto-low",
+ "hook_event_name": "SessionStart",
+ "source": "startup"
+ })
+ .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": "DROID-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=droid")
+ && request.contains("session_id=droid-session")
+ }),
+ "{recorded:?}"
+ );
+ }
+
// ── #992: per-repository server profiles ─────────────────────────────
/// Register `name` in `data_dir` with a token and the given roots.
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 9ded3fbf..1f16424a 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -353,6 +353,15 @@ fn grok_hooks_path_in(
.join("ai-memory.json"))
}
+/// `~/.factory/hooks.json` — Factory Droid's user-level lifecycle hooks
+/// (#1240), the event map itself with no wrapper key.
+pub(crate) fn droid_hooks_path() -> anyhow::Result<std::path::PathBuf> {
+ Ok(install_mcp::factory_home(
+ &home_dir().context("could not locate $HOME for ~/.factory/hooks.json")?,
+ )
+ .join("hooks.json"))
+}
+
/// `~/.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
@@ -872,6 +881,13 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(
resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;
apply_to_copilot_cli_hooks(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
+ AgentChoice::Droid => {
+ let path = match &args.config_file {
+ Some(path) => path.clone(),
+ None => droid_hooks_path()?,
+ };
+ apply_to_droid_hooks(&path, &server_url, auth, &config.data_dir, &args)
+ }
};
}
let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
@@ -1026,6 +1042,7 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(
&[COPILOT_CLI_PROFILE.events],
)
}
+ AgentChoice::Droid => render_droid(&server_url, auth, &config.data_dir, strategy),
}
}
@@ -1216,6 +1233,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
AgentChoice::Pool => return None,
AgentChoice::KiroCliV3 => kiro_cli_v3_hooks_path().ok()?,
AgentChoice::CopilotCli => copilot_cli_hooks_path().ok()?,
+ AgentChoice::Droid => droid_hooks_path().ok()?,
}
};
std::fs::read_to_string(path).ok()
@@ -1479,6 +1497,18 @@ fn infer_installed_mcp_config(
&["mcpServers", "ai-memory"],
"url",
)),
+ // `install-mcp --client droid` writes the bearer as the
+ // `${AI_MEMORY_AUTH_TOKEN}` reference Droid expands, not the token,
+ // so only the URL is inferred from it.
+ McpClient::Droid => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )
+ .map(|inferred| InferredMcpConfig {
+ auth_token: None,
+ ..inferred
+ })),
McpClient::Grok => infer_grok_mcp_config(&content),
McpClient::OpenCode | McpClient::OpenCode2 => infer_opencode_mcp_config(&content, client),
McpClient::Cursor => Ok(infer_json_mcp_config(
@@ -1632,6 +1662,7 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
// file to infer a server URL or token from.
AgentChoice::Hermes => None,
AgentChoice::CopilotCli => Some(McpClient::CopilotCli),
+ AgentChoice::Droid => Some(McpClient::Droid),
}
}
@@ -6771,6 +6802,138 @@ fn render_hermes_output(
out
}
+/// Merge ai-memory's entries into Droid's `hooks.json` (#1240), keeping
+/// every other entry in it, idempotently.
+///
+/// Droid reads the `hooks` key of the `settings.json` beside it only while
+/// `hooks.json` is absent, so creating the file over hooks kept there would
+/// switch them off without a word. That case is refused with the two ways
+/// out; an existing `hooks.json` is already the file Droid reads.
+fn apply_to_droid_hooks(
+ path: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ if !path.exists() {
+ let settings = path.with_file_name("settings.json");
+ if droid_settings_hold_hooks(&settings)? {
+ anyhow::bail!(
+ "{settings} keeps Droid hooks under its `hooks` key, and Droid reads those only \
+ while {path} does not exist, so creating {path} would switch them off. Either \
+ move that `hooks` object into {path} (the file holds the event map itself, \
+ with no `hooks` wrapper) and re-run this command, or add the entries \
+ `ai-memory install-hooks --agent droid` prints (without --apply) under \
+ the `hooks` key of {settings} yourself.",
+ settings = settings.display(),
+ path = path.display(),
+ );
+ }
+ }
+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
+ let payload = super::render_shared::build_droid_hooks_payload(
+ server_url,
+ auth_token,
+ Some(data_dir),
+ strategy,
+ );
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(|v| v.as_object())
+ .context("internal: build_droid_hooks_payload didn't return a hooks object")?;
+ let outcome = apply_atomic(path, |existing| {
+ mutate_json(existing, |root| {
+ for (event, value) in our_hooks {
+ overlay_event_hooks(root, 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!("{DROID_INSTALL_NOTES}");
+ Ok(())
+}
+
+const DROID_INSTALL_NOTES: &str = "\
+# NOTE: Droid adds SessionStart stdout to the session as context, so the
+# prior session's handoff is delivered automatically, and its own
+# SessionEnd closes the session.
+# NOTE: start a new droid session for it to load the new hooks.
+";
+
+/// Whether Droid's `settings.json` holds hook entries under `hooks`, the
+/// ones Droid reads while no `hooks.json` sits beside it. Parsed as JSONC
+/// since a settings file may carry comments; one that cannot be parsed is
+/// refused rather than guessed at.
+fn droid_settings_hold_hooks(settings: &Path) -> Result<bool> {
+ let text = match fs::read_to_string(settings) {
+ Ok(text) => text,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(e) => return Err(e).with_context(|| format!("reading {}", settings.display())),
+ };
+ let root: serde_json::Value = jsonc_parser::parse_to_ast(
+ &text,
+ &jsonc_parser::CollectOptions::default(),
+ &jsonc_parser::ParseOptions::default(),
+ )
+ .map_err(|e| {
+ anyhow::anyhow!(
+ "parsing {} to check whether Droid hooks live there: {e}",
+ settings.display()
+ )
+ })?
+ .value
+ .map_or(serde_json::Value::Null, Into::into);
+ Ok(match root.get("hooks") {
+ None | Some(serde_json::Value::Null) => false,
+ Some(serde_json::Value::Object(hooks)) => !hooks.is_empty(),
+ Some(_) => true,
+ })
+}
+
+/// Print Droid's `hooks.json` event map (dry-run counterpart of
+/// [`apply_to_droid_hooks`]).
+fn render_droid(
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ project_strategy: Option<&str>,
+) -> Result<()> {
+ let payload = super::render_shared::build_droid_hooks_payload(
+ server_url,
+ auth_token,
+ Some(data_dir),
+ project_strategy,
+ );
+ let serialized =
+ serde_json::to_string_pretty(&payload["hooks"]).context("serializing droid hook config")?;
+ println!("# Factory Droid CLI hook config — merge into ~/.factory/hooks.json (the");
+ println!("# file is this event map itself), or re-run with --apply to merge it in");
+ println!("# place. If you keep hooks under the `hooks` key of ~/.factory/settings.json");
+ println!("# instead, add these entries there: Droid reads settings.json hooks only");
+ println!("# while hooks.json does not exist.");
+ 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!("{DROID_INSTALL_NOTES}");
+ println!();
+ println!("{serialized}");
+ Ok(())
+}
+
fn render_devin(
hooks_dir: &Path,
server_url: &str,
@@ -7642,6 +7805,215 @@ mod tests {
}
}
+ fn droid_args(config_file: &Path) -> InstallHooksArgs {
+ InstallHooksArgs {
+ agent: AgentChoice::Droid,
+ config_file: Some(config_file.to_path_buf()),
+ ..default_hook_args()
+ }
+ }
+
+ /// `install-hooks --agent droid --apply` merges native `--agent droid`
+ /// commands into `hooks.json` (the bare event map), keeps every
+ /// third-party entry, and a re-apply changes nothing (#1240).
+ #[test]
+ fn droid_apply_merges_native_hooks_and_is_idempotent() {
+ let factory = TempDir::new().unwrap();
+ let data = TempDir::new().unwrap();
+ let hooks_json = factory.path().join("hooks.json");
+ fs::write(
+ &hooks_json,
+ serde_json::json!({
+ "PreToolUse": [{
+ "matcher": "Execute",
+ "hooks": [{"type": "command", "command": "/usr/local/bin/guard.sh", "timeout": 5}]
+ }],
+ "Notification": [{"hooks": [{"type": "command", "command": "notify-send hi"}]}]
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let args = droid_args(&hooks_json);
+
+ apply_to_droid_hooks(&hooks_json, "http://memory:49374", None, data.path(), &args).unwrap();
+ let first = fs::read_to_string(&hooks_json).unwrap();
+ apply_to_droid_hooks(&hooks_json, "http://memory:49374", None, data.path(), &args).unwrap();
+ assert_eq!(
+ first,
+ fs::read_to_string(&hooks_json).unwrap(),
+ "re-apply is a no-op"
+ );
+ let backups = fs::read_dir(factory.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!(root.get("hooks").is_none(), "hooks.json has no wrapper key");
+ for (event, script) in super::super::render_shared::DROID_EVENTS {
+ let entries = root[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 command = ours[0]["hooks"][0]["command"].as_str().unwrap();
+ let stem = script.trim_end_matches(".sh");
+ assert!(
+ command.contains(&format!(" hook --event {stem} --agent droid --server-url ")),
+ "{event}: {command}"
+ );
+ assert!(
+ !command.contains(".sh"),
+ "{event}: no script bundle: {command}"
+ );
+ }
+ assert!(root.get("SubagentStop").is_none());
+ // Third-party entries survive, in their own events and beside ours.
+ assert_eq!(
+ root["Notification"][0]["hooks"][0]["command"],
+ "notify-send hi"
+ );
+ let pre = root["PreToolUse"].as_array().unwrap();
+ assert_eq!(pre.len(), 2);
+ assert_eq!(pre[0]["matcher"], "Execute");
+ assert_eq!(pre[0]["hooks"][0]["command"], "/usr/local/bin/guard.sh");
+ }
+
+ /// 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 a
+ /// `hooks.json` that already exists, proceed.
+ #[test]
+ fn droid_apply_refuses_to_create_hooks_json_over_settings_hooks() {
+ let data = TempDir::new().unwrap();
+ for settings in [
+ r#"{"model": "x", "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "mine"}]}]}}"#,
+ // JSONC with comments still counts.
+ "{\n // user hooks\n \"hooks\": {\"Stop\": []},\n}\n",
+ r#"{"hooks": "unexpected"}"#,
+ ] {
+ let factory = TempDir::new().unwrap();
+ let hooks_json = factory.path().join("hooks.json");
+ let settings_json = factory.path().join("settings.json");
+ fs::write(&settings_json, settings).unwrap();
+ let error = apply_to_droid_hooks(
+ &hooks_json,
+ "http://memory:49374",
+ None,
+ data.path(),
+ &droid_args(&hooks_json),
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(
+ !hooks_json.exists(),
+ "{settings}: hooks.json must not be created"
+ );
+ assert_eq!(fs::read_to_string(&settings_json).unwrap(), settings);
+ assert!(error.contains("settings.json"), "{error}");
+ assert!(error.contains("hooks.json"), "{error}");
+ assert!(error.contains("--agent droid"), "{error}");
+ }
+
+ // Unparsable settings cannot prove the absence of hooks.
+ let factory = TempDir::new().unwrap();
+ let hooks_json = factory.path().join("hooks.json");
+ fs::write(factory.path().join("settings.json"), "{ not json").unwrap();
+ assert!(
+ apply_to_droid_hooks(
+ &hooks_json,
+ "http://memory:49374",
+ None,
+ data.path(),
+ &droid_args(&hooks_json)
+ )
+ .is_err()
+ );
+ assert!(!hooks_json.exists());
+
+ // Controls: no hooks in settings.json, or an empty `hooks` object.
+ for settings in [
+ r#"{"model": "x"}"#,
+ r#"{"hooks": {}}"#,
+ r#"{"hooks": null}"#,
+ ] {
+ let factory = TempDir::new().unwrap();
+ let hooks_json = factory.path().join("hooks.json");
+ fs::write(factory.path().join("settings.json"), settings).unwrap();
+ apply_to_droid_hooks(
+ &hooks_json,
+ "http://memory:49374",
+ None,
+ data.path(),
+ &droid_args(&hooks_json),
+ )
+ .unwrap();
+ assert!(hooks_json.exists(), "{settings}");
+ }
+
+ // An existing hooks.json is already what Droid reads.
+ let factory = TempDir::new().unwrap();
+ let hooks_json = factory.path().join("hooks.json");
+ fs::write(&hooks_json, "{}").unwrap();
+ fs::write(
+ factory.path().join("settings.json"),
+ r#"{"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "mine"}]}]}}"#,
+ )
+ .unwrap();
+ apply_to_droid_hooks(
+ &hooks_json,
+ "http://memory:49374",
+ None,
+ data.path(),
+ &droid_args(&hooks_json),
+ )
+ .unwrap();
+ let root: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&hooks_json).unwrap()).unwrap();
+ assert!(root["SessionStart"].is_array());
+ }
+
+ /// `install-mcp --client droid` writes the bearer as a
+ /// `${AI_MEMORY_AUTH_TOKEN}` reference; inferring hook settings from it
+ /// keeps the URL and never takes that reference for a token.
+ #[test]
+ fn droid_mcp_inference_keeps_url_and_drops_the_env_reference() {
+ let dir = TempDir::new().unwrap();
+ let mcp = dir.path().join("mcp.json");
+ fs::write(
+ &mcp,
+ serde_json::json!({"mcpServers": {"ai-memory": {
+ "type": "http",
+ "url": "http://memory:49374/mcp",
+ "headers": {"Authorization": "Bearer ${AI_MEMORY_AUTH_TOKEN}"}
+ }}})
+ .to_string(),
+ )
+ .unwrap();
+ let inferred = infer_installed_mcp_config(AgentChoice::Droid, Some(&mcp))
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ inferred.hook_server_url.as_deref(),
+ Some("http://memory:49374")
+ );
+ assert_eq!(inferred.auth_token, None);
+ assert_eq!(
+ mcp_client_for_agent(AgentChoice::Droid),
+ Some(McpClient::Droid)
+ );
+ }
+
fn default_hook_args() -> InstallHooksArgs {
InstallHooksArgs {
profile: None,
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index a9b3c7ec..5234983e 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -150,6 +150,7 @@ pub(crate) fn run_with_opencode_dialect(
McpClient::KiroCli => render_kiro_cli(&args)?,
McpClient::CommandCode => render_command_code(&args)?,
McpClient::CopilotCli => render_copilot_cli(&args)?,
+ McpClient::Droid => render_droid(&args)?,
McpClient::Swival => render_swival(&args)?,
McpClient::VsCodeCopilot => render_vscode_copilot(&args)?,
McpClient::Zed => render_zed(&args)?,
@@ -165,8 +166,8 @@ pub(crate) fn run_with_opencode_dialect(
/// without writing the token into the client's config.
///
/// - Claude Code gets the session-aware `ai-memory mcp-bridge` entry.
-/// - Codex and Prime Agent reference `AI_MEMORY_AUTH_TOKEN` by name, the
-/// form their writers already use and both clients document.
+/// - 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.
/// - Every other client that runs local commands gets a stdio entry for the
/// session-less bridge (`mcp-bridge --no-session-id`), in that client's own
@@ -178,7 +179,7 @@ pub(crate) fn run_with_opencode_dialect(
fn route_file_token(args: &mut InstallMcpArgs, token_file: &Path) -> Result<()> {
match args.client {
McpClient::ClaudeCode => args.session_aware = true,
- McpClient::Codex | McpClient::PrimeAgent => args.token_env_var = true,
+ McpClient::Codex | McpClient::PrimeAgent | McpClient::Droid => args.token_env_var = true,
McpClient::Pi => {}
McpClient::Zcode => bail!(
"this server's bearer token lives in {path} and ai-memory does not copy it into \
@@ -605,6 +606,9 @@ pub(crate) fn mcp_config_path_with(
// mcp-config.json there (project `.mcp.json` / `.github/mcp.json`
// files are left to `--config-file`).
McpClient::CopilotCli => copilot_home_in(env("COPILOT_HOME"))?.join("mcp-config.json"),
+ // Droid's user-level MCP servers live in ~/.factory/mcp.json; a
+ // project's `.factory/mcp.json` is left to --config-file.
+ McpClient::Droid => factory_home(&home()?).join("mcp.json"),
McpClient::Swival => {
let cwd = std::env::current_dir()
.context("could not resolve current dir for .swival/mcp.json default")?;
@@ -825,6 +829,13 @@ pub(crate) fn copilot_home_in(env_override: Option<std::ffi::OsString>) -> Resul
.join(".copilot"))
}
+/// 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.
+pub(crate) fn factory_home(home: &Path) -> PathBuf {
+ home.join(".factory")
+}
+
/// Prime Agent's agent directory: `$PRIME_AGENT_CODING_AGENT_DIR` when set and
/// not blank, otherwise `~/.prime/agent`. The override is injected to keep
/// path tests process-local.
@@ -945,6 +956,12 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {
" Prime Agent reads the token from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch prime-agent."
);
}
+ if matches!(args.client, McpClient::Droid) && (args.auth_token.is_some() || args.token_env_var)
+ {
+ println!(
+ " Droid expands ${{{PRIME_AGENT_TOKEN_ENV}}} in the Authorization header; export it where you launch droid, or the server fails to connect."
+ );
+ }
if matches!(args.client, McpClient::Codex) && args.token_env_var {
println!(
" Codex reads the token from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex."
@@ -1004,6 +1021,7 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {
| McpClient::KiroCli
| McpClient::CommandCode
| McpClient::CopilotCli
+ | McpClient::Droid
| McpClient::Swival
| McpClient::PrimeAgent => Some(JsonMcpLocation::RootMcpServers),
McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),
@@ -1606,6 +1624,21 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
}
entry.insert("tools".into(), json!(["*"]));
}
+ McpClient::Droid => {
+ // Droid's `mcp.json` HTTP entry: `type: "http"` + `url`, optional
+ // `headers`. Droid expands a bare `${NAME}` only inside
+ // `headers` (and stdio env / OAuth fields), never in `url`, so
+ // the URL stays literal and the bearer is referenced by name,
+ // which also keeps the token out of the file (#1240).
+ entry.insert("type".into(), json!("http"));
+ entry.insert("url".into(), json!(server_url));
+ if args.auth_token.is_some() || args.token_env_var {
+ entry.insert(
+ "headers".into(),
+ json!({"Authorization": format!("Bearer ${{{PRIME_AGENT_TOKEN_ENV}}}")}),
+ );
+ }
+ }
McpClient::PrimeAgent => {
// Prime Agent 0.10 counts a user HTTP server as connected, and
// names it to the model, only with an OAuth grant or a
@@ -2346,6 +2379,25 @@ fn render_copilot_cli(args: &InstallMcpArgs) -> Result<String> {
))
}
+fn render_droid(args: &InstallMcpArgs) -> Result<String> {
+ Ok(format!(
+ "# Factory Droid CLI — merge into ~/.factory/mcp.json, or re-run with\n\
+ # --apply to merge it in place preserving other servers. A project's\n\
+ # `.factory/mcp.json` also works: pass that path via --config-file.\n\
+ #\n\
+ # The equivalent CLI registration is:\n\
+ # droid mcp add {name} {url} --type http\n\
+ # Droid expands ${{VAR}} only in headers, so the URL is literal and a\n\
+ # bearer is read from ${env} where droid runs.\n\
+ # Pair with `ai-memory install-hooks --agent droid` for capture.\n\
+ {snippet}\n",
+ name = args.name,
+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),
+ env = PRIME_AGENT_TOKEN_ENV,
+ snippet = render_json_mcp_fragment(args)?,
+ ))
+}
+
fn render_swival(args: &InstallMcpArgs) -> Result<String> {
Ok(format!(
"# Swival CLI — merge into .swival/mcp.json in the project root
@@ -2434,6 +2486,81 @@ mod tests {
}
}
+ /// Droid's `mcp.json` HTTP entry (#1240): the URL is literal (Droid
+ /// never expands variables there), and a configured bearer becomes the
+ /// `${AI_MEMORY_AUTH_TOKEN}` reference Droid expands in headers, never
+ /// the token itself. No bearer, no header.
+ #[test]
+ fn droid_entry_keeps_url_literal_and_references_the_token_variable() {
+ let entry = build_json_mcp_entry(&args_with_token(McpClient::Droid)).unwrap();
+ assert_eq!(
+ entry,
+ json!({
+ "type": "http",
+ "url": "http://127.0.0.1:49374/mcp",
+ "headers": {"Authorization": "Bearer ${AI_MEMORY_AUTH_TOKEN}"},
+ })
+ );
+ assert!(!entry.to_string().contains("test-token-deadbeef"));
+ let plain = build_json_mcp_entry(&args_for(McpClient::Droid)).unwrap();
+ assert_eq!(
+ plain,
+ json!({"type": "http", "url": "http://127.0.0.1:49374/mcp"})
+ );
+ let rendered = render_droid(&args_with_token(McpClient::Droid)).unwrap();
+ assert!(rendered.contains("\"mcpServers\""), "{rendered}");
+ assert!(rendered.contains("~/.factory/mcp.json"), "{rendered}");
+ assert!(!rendered.contains("test-token-deadbeef"), "{rendered}");
+ }
+
+ /// `--apply` merges into `~/.factory/mcp.json`'s `mcpServers`, keeping
+ /// other servers and top-level keys, and a re-run is a no-op.
+ #[test]
+ fn droid_apply_merges_into_mcp_servers_and_is_idempotent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = tmp.path().join("mcp.json");
+ std::fs::write(
+ &file,
+ json!({"mcpServers": {"other": {"type": "stdio", "command": "x"}}, "keep": 1})
+ .to_string(),
+ )
+ .unwrap();
+ let mut args = args_for(McpClient::Droid);
+ args.apply = true;
+ args.config_file = Some(file.clone());
+ args.server_url = Some("http://memory:49374/mcp".into());
+ apply_to_config_file(&args).unwrap();
+ let first = std::fs::read_to_string(&file).unwrap();
+ apply_to_config_file(&args).unwrap();
+ assert_eq!(first, std::fs::read_to_string(&file).unwrap());
+ let root: serde_json::Value = serde_json::from_str(&first).unwrap();
+ assert_eq!(root["keep"], 1);
+ assert_eq!(root["mcpServers"]["other"]["command"], "x");
+ assert_eq!(
+ root["mcpServers"]["ai-memory"],
+ json!({"type": "http", "url": "http://memory:49374/mcp"})
+ );
+ assert_eq!(
+ existing_entry_endpoint(McpClient::Droid, &file, "ai-memory").unwrap(),
+ Some("http://memory:49374/mcp".into())
+ );
+ }
+
+ #[test]
+ fn droid_mcp_config_lives_under_dot_factory() {
+ assert_eq!(
+ factory_home(Path::new("/home/me")).join("mcp.json"),
+ Path::new("/home/me/.factory/mcp.json")
+ );
+ if let Ok(path) = mcp_config_path(McpClient::Droid) {
+ assert!(
+ path.ends_with(Path::new(".factory").join("mcp.json")),
+ "{}",
+ path.display()
+ );
+ }
+ }
+
#[test]
fn muse_entry_uses_documented_streamable_http_shape() {
let entry = build_json_mcp_entry(&args_with_token(McpClient::Muse)).unwrap();
@@ -3458,6 +3585,7 @@ mod tests {
McpClient::KiroCli => render_kiro_cli(&args).unwrap(),
McpClient::CommandCode => render_command_code(&args).unwrap(),
McpClient::CopilotCli => render_copilot_cli(&args).unwrap(),
+ McpClient::Droid => render_droid(&args).unwrap(),
McpClient::Swival => render_swival(&args).unwrap(),
McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),
McpClient::Zed => render_zed(&args).unwrap(),
@@ -3534,6 +3662,7 @@ mod tests {
McpClient::KiroCli,
McpClient::CommandCode,
McpClient::CopilotCli,
+ McpClient::Droid,
McpClient::Swival,
McpClient::VsCodeCopilot,
McpClient::Zed,
@@ -3573,6 +3702,7 @@ mod tests {
McpClient::KiroCli => render_kiro_cli(&args).unwrap(),
McpClient::CommandCode => render_command_code(&args).unwrap(),
McpClient::CopilotCli => render_copilot_cli(&args).unwrap(),
+ McpClient::Droid => render_droid(&args).unwrap(),
McpClient::Swival => render_swival(&args).unwrap(),
McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),
McpClient::Zed => render_zed(&args).unwrap(),
@@ -3641,9 +3771,10 @@ mod tests {
!text.contains(FILE_TOKEN),
"token leaked into {client:?}: {text}"
);
- assert!(
- !text.contains("Authorization"),
- "{client:?} got a header: {text}"
+ assert_eq!(
+ text.contains("Authorization"),
+ client == McpClient::Droid,
+ "only Droid takes a header, and only a variable reference: {text}"
);
match client {
McpClient::Codex => assert!(
@@ -3653,6 +3784,13 @@ mod tests {
McpClient::PrimeAgent => {
assert!(text.contains("\"bearerTokenEnvVar\""), "{text}");
}
+ McpClient::Droid => {
+ assert!(
+ text.contains("\"Bearer ${AI_MEMORY_AUTH_TOKEN}\""),
+ "{text}"
+ );
+ assert!(!text.contains("mcp-bridge"), "{text}");
+ }
_ => {
let endpoint = existing_entry_endpoint(client, &file, "ai-memory")
.unwrap()
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 348f930e..da7bfbeb 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -102,6 +102,27 @@ pub(crate) const COPILOT_CLI_EVENTS: [(&str, &str); 10] = [
("SubagentStop", "subagent-stop.sh"),
];
+/// Factory Droid CLI lifecycle events ai-memory hooks (#1240). Each pair is
+/// `(event-name-in-~/.factory/hooks.json, native hook-event script stem)`;
+/// Droid has no script bundle, so the `.sh` name only carries the event
+/// token the native command is rendered with.
+///
+/// Droid's documented vocabulary is Claude Code's minus `SubagentStart`
+/// (0.240.0). `SubagentStop` is left out with it: without the start
+/// boundary there is no subagent session to forget, and its payload
+/// (`task_name`, `task_result`) is not Claude's. `Notification` carries no
+/// capture. Droid fires a real `SessionEnd`, so no `finalize-session` step is
+/// needed.
+pub(crate) const DROID_EVENTS: [(&str, &str); 7] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+ ("SessionEnd", "session-end.sh"),
+];
+
/// Kiro CLI v2-engine lifecycle events. Each pair is
/// `(trigger-name-in-agent-config, POSIX hook-script-filename)`.
///
@@ -1018,6 +1039,36 @@ pub(crate) fn build_devin_payload_with_data_dir(
)
}
+/// `{"hooks": <event map>}` for Factory Droid (#1240). `~/.factory/hooks.json`
+/// holds the event map itself, with no wrapper key, in Claude Code's nested
+/// shape (`"Event": [{"matcher": "", "hooks": [{"type": "command",
+/// "command": …}]}]`). Droid runs each `command` through
+/// a shell with the Claude Code-shaped event JSON on stdin, so every entry
+/// invokes the native `ai-memory hook` command; there is no script bundle to
+/// fall back to, so the platform is always a native one, whatever
+/// `AI_MEMORY_HOOK_PLATFORM` asks for. An empty matcher fires on every tool
+/// and every SessionStart source.
+pub(crate) fn build_droid_hooks_payload(
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: Option<&Path>,
+ project_strategy: Option<&str>,
+) -> Value {
+ build_hook_payload_for_platform(
+ &DROID_EVENTS,
+ Path::new(""),
+ server_url,
+ auth_token,
+ HookShape::Nested,
+ HookCommandContext::new(
+ HookCommandPlatform::native(),
+ "droid",
+ data_dir,
+ project_strategy,
+ ),
+ )
+}
+
/// 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-memory
@@ -1690,6 +1741,17 @@ impl HookCommandPlatform {
})
}
+ /// The native binary command for this OS, ignoring any override: for an
+ /// agent with no script bundle a script platform would name files that
+ /// were never staged.
+ const fn native() -> Self {
+ if cfg!(windows) {
+ Self::WindowsNative
+ } else {
+ Self::PosixNative
+ }
+ }
+
/// Script fallback for setup-agent / docker-host snippets. Respects an
/// explicit override, but defaults to the shell command because setup-agent
/// copies scripts, not a host-local native binary.
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 66d80198..c3f3b3ed 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -114,6 +114,12 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {
emit_hermes(&args)?;
return Ok(());
}
+ // Droid has no script bundle either: its hooks.json runs the native
+ // `hook` command.
+ if matches!(args.agent, AgentChoice::Droid) {
+ emit_droid(&args)?;
+ return Ok(());
+ }
let Some(agent_sub) = args.agent.script_hook_subdir() else {
bail!("internal: generated integration should have returned before staging hooks")
};
@@ -210,7 +216,8 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {
| AgentChoice::Openclaw
| AgentChoice::Zero
| AgentChoice::Zcode
- | AgentChoice::Hermes => {
+ | AgentChoice::Hermes
+ | AgentChoice::Droid => {
bail!(
"internal: generated integration should have returned before emitting staged hooks"
)
@@ -309,6 +316,31 @@ fn emit_hermes(args: &SetupAgentArgs) -> Result<()> {
Ok(())
}
+/// Print the event map for `~/.factory/hooks.json` (#1240). No scripts are
+/// staged: each entry runs the ai-memory binary's native `hook` command with
+/// Droid's event JSON on stdin, so the binary must be reachable on the host
+/// that runs Droid.
+fn emit_droid(args: &SetupAgentArgs) -> Result<()> {
+ let payload = crate::commands::render_shared::build_droid_hooks_payload(
+ &args.server_url,
+ args.auth_token.as_deref(),
+ None,
+ None,
+ );
+ let serialized =
+ serde_json::to_string_pretty(&payload["hooks"]).context("serializing Droid hook config")?;
+ println!("# Factory Droid — merge into ~/.factory/hooks.json (the file is the");
+ println!("# event map itself). The `command` must be an ai-memory binary reachable");
+ println!("# on the host that runs Droid; prefer `ai-memory install-hooks --agent");
+ println!("# droid --apply` from that host so the path is resolved for you.");
+ if args.auth_token.is_some() {
+ println!("# Treat hooks.json as sensitive (chmod 600).");
+ }
+ println!();
+ println!("{serialized}");
+ Ok(())
+}
+
fn normalise_hook_server_url(url: &str) -> String {
url.trim().trim_end_matches('/').to_string()
}
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 6af44509..c789f866 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -252,6 +252,12 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
install_hooks::devin_config_path()?,
HookConfigShape::NestedHooksKey,
),
+ // Droid's hooks.json is the event map itself, like Devin's
+ // hooks.v1.json.
+ (
+ install_hooks::droid_hooks_path()?,
+ HookConfigShape::FlatHookFile,
+ ),
]);
for (path, shape) in hook_files {
if !path.exists() {
@@ -415,6 +421,7 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
KiroCli,
CommandCode,
CopilotCli,
+ Droid,
Swival,
Muse,
PrimeAgent,
@@ -1335,6 +1342,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {
| McpClient::KiroCli
| McpClient::CommandCode
| McpClient::CopilotCli
+ | McpClient::Droid
| McpClient::Swival
| McpClient::Devin
| McpClient::PrimeAgent => Some(&["mcpServers"]),
diff --git a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs
index c9807ce4..d5bb705a 100644
--- a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs
@@ -476,6 +476,7 @@ mod slow {
"kiro-cli",
"command-code",
"copilot-cli",
+ "droid",
"swival",
"vscode-copilot",
"zed",
diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rs
index 083c43a2..4a9a53af 100644
--- a/crates/ai-memory-cli/tests/suite/removal.rs
+++ b/crates/ai-memory-cli/tests/suite/removal.rs
@@ -1034,6 +1034,80 @@ fn zcode_mcp_install_and_uninstall_round_trip_preserves_siblings() {
);
}
+/// Factory Droid (#1240): `install-mcp` and `install-hooks` merge into
+/// `~/.factory/mcp.json` and the bare `~/.factory/hooks.json` event map
+/// around the user's own entries, and `uninstall` removes only ai-memory's.
+#[test]
+fn droid_install_and_uninstall_round_trip_preserves_user_entries() {
+ let _guard = cli_test_lock();
+ let home = tempfile::tempdir().unwrap();
+ let mcp = home.path().join(".factory/mcp.json");
+ let hooks = home.path().join(".factory/hooks.json");
+ write_file(
+ &mcp,
+ r#"{"mcpServers":{"other":{"type":"http","url":"https://other.example/mcp"}}}"#,
+ );
+ write_file(
+ &hooks,
+ r#"{"PreToolUse":[{"matcher":"Execute","hooks":[{"type":"command","command":"/usr/local/bin/guard.sh"}]}]}"#,
+ );
+
+ for args in [
+ &["install-mcp", "--client", "droid", "--apply"][..],
+ &["install-hooks", "--agent", "droid", "--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(&mcp).unwrap()).unwrap();
+ assert_eq!(installed["mcpServers"]["ai-memory"]["type"], "http");
+ assert_eq!(
+ installed["mcpServers"]["other"]["url"],
+ "https://other.example/mcp"
+ );
+ let wired: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&hooks).unwrap()).unwrap();
+ let pre = wired["PreToolUse"].as_array().unwrap();
+ assert_eq!(pre.len(), 2, "{wired}");
+ assert!(
+ pre[1]["hooks"][0]["command"]
+ .as_str()
+ .unwrap()
+ .contains("--agent droid"),
+ "{wired}"
+ );
+ assert!(wired["SessionEnd"].is_array(), "{wired}");
+
+ 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 removed: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&mcp).unwrap()).unwrap();
+ assert!(removed["mcpServers"].get("ai-memory").is_none());
+ assert_eq!(
+ removed["mcpServers"]["other"]["url"],
+ "https://other.example/mcp"
+ );
+ let unwired = std::fs::read_to_string(&hooks).unwrap();
+ assert!(!unwired.contains("--agent droid"), "{unwired}");
+ let unwired: serde_json::Value = serde_json::from_str(&unwired).unwrap();
+ assert_eq!(
+ unwired["PreToolUse"][0]["hooks"][0]["command"],
+ "/usr/local/bin/guard.sh"
+ );
+}
+
#[test]
fn swival_mcp_install_and_uninstall_round_trip_from_nested_directory() {
let _guard = cli_test_lock();
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 145e1885..5ec0ae35 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1385,8 +1385,8 @@ needs a manual change.
A token read from the file is never written into a harness config or onto a
command line. `install-mcp` gives Claude Code the session-aware
-`ai-memory mcp-bridge` stdio entry, which reads the file itself; Codex and
-Prime Agent reference `AI_MEMORY_AUTH_TOKEN` by name; every other client gets
+`ai-memory mcp-bridge` stdio entry, which reads the file itself; Codex,
+Prime Agent and Factory Droid reference `AI_MEMORY_AUTH_TOKEN` by name; every other client gets
a stdio entry, in its own config format, for `ai-memory mcp-bridge
--no-session-id`. ZCode keeps HTTP entries only and is refused.
`install-hooks --apply` persists it to the hook credential files and
diff --git a/docs/install.md b/docs/install.md
index 1f844e31..53523a89 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -18,7 +18,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, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Pool, OpenClaw, VS Code Copilot, Zed, and MCP-only recipes for Factory Droid, 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, 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)
@@ -1530,6 +1530,59 @@ would point every teammate at one person's install and server.
managed workstream harness (see [managed workstreams](managed-workstreams.md));
`install-mcp --client copilot` remains the VS Code Copilot client.
+### Factory Droid
+
+Droid (`droid`) keeps its user config in `~/.factory`. `install-mcp --client
+droid` (alias `factory-droid`) merges the server entry into `mcp.json` there,
+and `install-hooks --agent droid` merges lifecycle hooks into `hooks.json`,
+keeping every entry you already have in either file (#1240):
+
+```bash
+ai-memory install-mcp --client droid --apply \
+ --server-url "http://homelab:49374/mcp"
+ai-memory install-hooks --agent droid --apply \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+```
+
+The MCP entry is `{"type": "http", "url": …}` under `mcpServers`. Droid
+expands `${NAME}` in `headers` but never in `url`, so the URL is written
+literally. When the server has a bearer token, the entry gets
+`"headers": {"Authorization": "Bearer ${AI_MEMORY_AUTH_TOKEN}"}` instead of
+the token, so export `AI_MEMORY_AUTH_TOKEN` in the shell that starts droid:
+Droid fails that connection, naming the variable, when it is unset. A
+project's `.factory/mcp.json` also works (pass it with `--config-file`), but
+Droid's docs advise keeping auth headers out of that committed file. Without a
+token, `droid mcp add ai-memory http://127.0.0.1:49374/mcp --type http` writes
+the same entry.
+
+`~/.factory/hooks.json` holds the event map itself, with no `hooks` wrapper.
+Droid sends Claude Code-shaped JSON on stdin (`session_id`, `cwd`,
+`tool_name`, `tool_input`, `tool_response`), so each entry runs the native
+`ai-memory hook --event … --agent droid` command; there is no script bundle,
+and the local spool, bearer auth and `[capture] ignore_paths` apply. Droid's
+`Read`, `Create`, `Edit`, `ApplyPatch` (a Codex-style patch envelope),
+`LS`, `Grep`, `Glob` and `Execute` tools are mapped to the file, search and
+shell families those exclusions use, verified against the Droid 0.240.0 tool
+schemas. Droid payloads carry no tool-call id. Seven events are wired:
+`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`,
+`Stop` and `SessionEnd`. `SubagentStop` is left out because Droid has no
+`SubagentStart` to pair it with.
+
+Droid reads the `hooks` key of `~/.factory/settings.json` only while
+`hooks.json` does not exist. If your hooks live there, `--apply` refuses to
+create `hooks.json`, which would switch them off, and says so. Either move
+that `hooks` object into `~/.factory/hooks.json` and run the command again, or
+merge the entries `ai-memory install-hooks --agent droid` prints (without
+`--apply`) under the `hooks` key of `settings.json` yourself.
+
+The `SessionStart` hook delivers the prior session's handoff through
+`hookSpecificOutput.additionalContext`, which Droid adds to the session, and
+Droid's own `SessionEnd` closes the session, so `finalize-session` is not
+needed. Start a new droid session after installing so it loads the hooks.
+`ai-memory setup --agent droid` runs both installers; `setup` does not detect
+Droid on its own, and no managed workstream (`ai-memory run droid`) is claimed.
+
### Hermes Agent (Nous Research)
Hermes declares lifecycle hooks in the `hooks:` block of
@@ -1930,33 +1983,6 @@ token has to be written into that file, so keep the file private. All of
these clients speak HTTP MCP natively; `ai-memory mcp-bridge` is a Claude
Code-only adapter and is not needed.
-##### Factory Droid
-
-Droid (`droid`) reads MCP servers from `~/.factory/mcp.json` (user),
-`.factory/mcp.json` in the project root, or a `.factory/mcp.json` in an
-ancestor folder. It reloads when the file changes. Droid expands `${NAME}` in
-`headers` values (not in `url`), and its docs say to keep auth headers in the
-user file rather than the committed project file:
-
-```json
-{
- "mcpServers": {
- "ai-memory": {
- "type": "http",
- "url": "http://127.0.0.1:49374/mcp",
- "headers": { "Authorization": "Bearer ${AI_MEMORY_AUTH_TOKEN}" }
- }
- }
-}
-```
-
-Leave out `headers` when the server has no bearer token. An unset variable
-makes Droid fail that connection with an error naming it. Without a token,
-`droid mcp add ai-memory http://127.0.0.1:49374/mcp --type http` writes the
-same entry to the user file. Documented for Droid CLI 0.237.0.
-Sources: <https://docs.factory.com/cli/configuration/mcp>,
-<https://docs.factory.com/changelog/cli-updates>.
-
##### Warp
Warp reads `~/.warp/.mcp.json` and, after you approve it, a project's
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index f12c79c8..3b2d3c93 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -3,7 +3,7 @@
For a custom tool, start with the [programmatic memory guide](programmatic-memory.md).
It shows direct MCP writes, queries and handoffs without a native hook adapter.
-Factory Droid, Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no
+Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no
`install-mcp` client; their hand-written recipes are in
[`install.md`](install.md#clients-without-an-install-mcp-writer).
@@ -16,8 +16,9 @@ Factory Droid, 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`) and Prime Agent (`bearerTokenEnvVar`)
-> name `AI_MEMORY_AUTH_TOKEN`, which you export where you start them. Every
+> entry; 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
> `ai-memory mcp-bridge --no-session-id --server-url <url>`: the bridge reads
> the token file at launch and forwards no session id, so the client passes
@@ -316,6 +317,50 @@ nothing is pending.
---
+## Factory Droid
+
+**Status:** MCP and lifecycle hooks are supported (#1240); the `SessionStart`
+hook injects the pending handoff and Droid's `SessionEnd` closes the session.
+No managed workstream.
+
+**Config files:** `~/.factory/mcp.json` for MCP and `~/.factory/hooks.json`
+for lifecycle hooks.
+
+```bash
+ai-memory install-mcp --client droid --apply \
+ --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"
+ai-memory install-hooks --agent droid --apply \
+ --server-url "http://homelab:49374" --auth-token "$TOKEN"
+```
+
+The MCP installer merges an HTTP entry into the root `mcpServers` map,
+preserving other servers. Droid expands `${NAME}` only in `headers`, so the
+URL stays literal and the bearer is a variable reference, never the token:
+
+```json
+{
+ "mcpServers": {
+ "ai-memory": {
+ "type": "http",
+ "url": "http://homelab:49374/mcp",
+ "headers": { "Authorization": "Bearer ${AI_MEMORY_AUTH_TOKEN}" }
+ }
+ }
+}
+```
+
+Export `AI_MEMORY_AUTH_TOKEN` where you launch droid; an unset variable makes
+Droid fail the connection. Without a bearer the entry has no `headers`.
+`install-hooks --agent droid` run without `--server-url` reads the URL back
+from this entry (not the token, which is only a reference there). The hook
+installer, its native commands and the `settings.json` refusal are described
+in [`install.md`](install.md#factory-droid).
+
+- Sources: <https://docs.factory.com/cli/configuration/mcp>,
+ <https://docs.factory.com/harness/hooks>
+
+---
+
## VS Code GitHub Copilot
**Status:** ✅ MCP supported (workspace-default). ❌ No lifecycle hooks
diff --git a/docs/security.md b/docs/security.md
index 4aaa5e99..7e64bd1e 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -8,8 +8,8 @@ only) and records `[auth].bearer_token_file`; the server then refuses every
route 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 is
never pasted into a harness config or passed on a command line. Claude Code
-runs the session-aware bridge, Codex and Prime Agent reference the token as
-`$AI_MEMORY_AUTH_TOKEN`, and every other MCP client `install-mcp` supports
+runs the session-aware bridge, Codex, Prime Agent and Factory Droid reference
+the token as `$AI_MEMORY_AUTH_TOKEN`, and every other MCP client `install-mcp` supports
runs `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.md
index e25e5393..e90ea2a0 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -48,7 +48,7 @@
| 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`). |
| GrizzyBot | Supported | [GrizzyBot](https://github.com/Foscoe63/GrizzyBot), a native macOS agent app, ships its own ai-memory bridge: it posts lifecycle events to `/hook` with `agent=grizzybot` (alias `grizzy-bot`) and talks to `/mcp` directly, so there is nothing for `install-hooks` or `install-mcp` to write. Sessions are attributed to `grizzybot`, and its Claude Code-shaped tool payloads (`tool_name`/`tool_input`/`tool_use_id`) are stored as closed-schema tool families, never tool names or arguments. The bridge is maintained in the GrizzyBot repository; review it before pointing it at a shared server. No managed workstream. |
-| Factory Droid | MCP-only (documented) | Native HTTP entry in `~/.factory/mcp.json` (`type: "http"`, `url`, `headers`); the bearer header reads `${AI_MEMORY_AUTH_TOKEN}`, which Droid expands. No `install-mcp` client and no lifecycle hooks installed. Documented against Droid CLI 0.237.0, not yet verified end to end. See [`install.md`](install.md#factory-droid). |
+| Factory Droid | Supported | MCP config (`install-mcp --client droid`, alias `factory-droid` → `~/.factory/mcp.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks (`install-hooks --agent droid` → `~/.factory/hooks.json`) (#1240). The URL is written literally because Droid expands `${VAR}` only in headers; a bearer becomes `Authorization: Bearer ${AI_MEMORY_AUTH_TOKEN}`, so export that variable where droid runs (a token-file install gets the same reference, never the token). Droid sends Claude Code-shaped hook payloads, so each entry runs the native `ai-memory hook --event … --agent droid` command (no script bundle) and native commands enforce capture exclusions over Droid's `Read`, `Create`, `Edit`, `ApplyPatch`, `LS`, `Grep`, `Glob` and `Execute` tools, verified against the Droid 0.240.0 tool schemas; Droid payloads carry no tool-call id. Seven events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`, `SessionEnd`. The `SessionStart` hook delivers the prior session's handoff through `hookSpecificOutput.additionalContext`, and Droid's own `SessionEnd` closes the session, so no `finalize-session` step is needed. `--apply` merges around your own entries, and refuses to create `hooks.json` while `~/.factory/settings.json` keeps hooks under its `hooks` key, because Droid reads those only while `hooks.json` is absent. The issue reporter ran capture and recall end to end with this hook wiring on Droid 0.239.0; the handoff injection follows Droid's documented contract and has not been run end to end yet. No managed workstream (`ai-memory run droid`). See [`install.md`](install.md#factory-droid). |
| Warp | MCP-only (documented) | `url` + `headers` entry in `~/.warp/.mcp.json` or **Settings > Agents > MCP servers**; no documented env-var expansion in headers. No `install-mcp` client and no lifecycle hooks. Documented against Warp v0.2026.10.07.08.29, not yet verified end to end. See [`install.md`](install.md#warp). |
| Cline | MCP-only (documented) | `type: "streamableHttp"` entry under `mcpServers` (CLI: `~/.cline/data/settings/cline_mcp_settings.json`; extension: **MCP Servers > Configure**); without `type` Cline uses legacy SSE. No `install-mcp` client and no lifecycle hooks installed. Documented against Cline extension 4.1.23 / CLI 3.0.70, not yet verified end to end. See [`install.md`](install.md#cline). |
| Kilo Code | MCP-only (documented) | `type: "remote"` entry under `mcp` in `~/.config/kilo/kilo.jsonc` (shared by the VS Code extension and the CLI), with `"oauth": false` and the bearer header from `{env:AI_MEMORY_AUTH_TOKEN}`. No `install-mcp` client and no lifecycle hooks installed. Documented against Kilo Code 7.8.8, not yet verified end to end. See [`install.md`](install.md#kilo-code). |