From dea53731232cd8d775aa0d2108eb2312eac39b40 Mon Sep 17 00:00:00 2001 From: Bertho Joris Date: Fri, 31 Jul 2026 13:51:37 +0700 Subject: [PATCH 1/5] feat(cli): add native hooks adapter for Droid (Factory.ai) Droid ships a first-party hooks system (~/.factory/hooks.json) using the same manifest shape as Codex/Claude Code. `agentmemory connect droid --with-hooks` now merges the bundled hooks.droid.json into it, covering SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, and SessionEnd via the existing buildMergedHooks merge/re-install logic. Also fixes a Windows test-isolation bug in connect-new-agents.test.ts where os.homedir() reads USERPROFILE (not HOME), which was silently letting adapter tests write into the real user home directory. Co-Authored-By: Claude Sonnet 5 --- README.md | 2 +- plugin/hooks/hooks.droid.json | 55 ++++++++++++++++ src/cli/connect/codex-hooks.ts | 18 ++++-- src/cli/connect/droid.ts | 76 +++++++++++++++++++++- src/cli/connect/json-mcp-adapter.ts | 25 ++++++++ src/cli/connect/types.ts | 9 +-- test/connect-new-agents.test.ts | 99 +++++++++++++++++++++++++++++ test/droid-connect-hooks.test.ts | 75 ++++++++++++++++++++++ 8 files changed, 347 insertions(+), 12 deletions(-) create mode 100644 plugin/hooks/hooks.droid.json create mode 100644 test/droid-connect-hooks.test.ts diff --git a/README.md b/README.md index 48f4045cd6..ff37d7aeb6 100644 --- a/README.md +++ b/README.md @@ -677,7 +677,7 @@ The agentmemory entry is the **same MCP server block** across every host that us | **Cline (CLI)** | `~/.cline/mcp.json` | `agentmemory connect cline` writes the standard `mcpServers` block. VS Code extension users: paste the same block via Cline Settings → MCP Servers → Edit JSON. | | **Continue.dev** | `~/.continue/config.yaml` (preferred) or `config.json` (legacy) | `agentmemory connect continue` creates `config.yaml` from scratch when neither exists, or modifies existing `config.json`. **If you already have `config.yaml`** the adapter prints the exact block to paste under `mcpServers:` — it won't silently rewrite your yaml because preserving comments and anchors safely needs a YAML parser the package doesn't ship. Continue uses array form (not object) for `mcpServers`. | | **Zed** | `~/.config/zed/settings.json` | `agentmemory connect zed` writes under `context_servers` (Zed's key, NOT `mcpServers`). Remote MCP servers can be wired via `{"url": "..."}` instead. | -| **Droid (Factory.ai)** | `~/.factory/mcp.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `/.factory/mcp.json`. The `/mcp` slash command inside droid lists configured servers. | +| **Droid (Factory.ai)** | `~/.factory/mcp.json` + `~/.factory/hooks.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `/.factory/mcp.json`. The `/mcp` slash command inside droid lists configured servers. Run `agentmemory connect droid --with-hooks` to also wire Droid's native hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, SessionEnd) into `~/.factory/hooks.json` for zero-effort auto-capture, same merge/re-install behavior as the Codex and Claude Code hook installers. | | **Goose** | Goose MCP settings UI | Same `mcpServers` block — use `goose configure` → Add Extension → MCP. Direct YAML edit at `~/.config/goose/config.yaml` is supported but the schema uses `extensions:` + `cmd` (not `mcpServers:` + `command`). | | **Aider** | n/a | Talk to the REST API directly: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. | | **Any agent (32+)** | n/a | `npx skillkit install agentmemory` auto-detects the host and merges. | diff --git a/plugin/hooks/hooks.droid.json b/plugin/hooks/hooks.droid.json new file mode 100644 index 0000000000..ff38349593 --- /dev/null +++ b/plugin/hooks/hooks.droid.json @@ -0,0 +1,55 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-start.mjs\"" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/prompt-submit.mjs\"" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Edit|Write|Read|Glob|Grep", + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-tool-use.mjs\"" + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/post-tool-use.mjs\"" + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-end.mjs\"" + } + ] + } + ] + } +} diff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.ts index ad19877b1c..f2a3a3bd67 100644 --- a/src/cli/connect/codex-hooks.ts +++ b/src/cli/connect/codex-hooks.ts @@ -3,17 +3,27 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; /** - * Workaround for openai/codex#16430 — Codex Desktop does not dispatch + * Shared merge engine for writing agentmemory's bundled hook scripts into + * a host's global, user-scope hooks config. Originally built as a + * workaround for openai/codex#16430 — Codex Desktop does not dispatch * plugin-local `hooks.json` even though both `CodexHooks` and `PluginHooks` * feature flags are stable + default-enabled in * `codex-rs/features/src/lib.rs`. Until upstream fixes plugin-scope * dispatch, the same hook commands can be mirrored into the global * `~/.codex/hooks.json`, which is loaded reliably. * - * This module builds that mirror, with `${CLAUDE_PLUGIN_ROOT}` resolved to + * The same merge logic now also backs Claude Code's `--with-hooks` + * fallback (`~/.claude/settings.json`, #508 workaround) and Droid's + * native `~/.factory/hooks.json` install, since both hosts consume the + * identical `{ hooks: { : [{ matcher?, hooks: [{ type, command }] }] } }` + * shape — only the bundled manifest file passed to `buildMergedHooks` + * differs per host. + * + * This module builds that merge, with `${CLAUDE_PLUGIN_ROOT}` resolved to * the bundled `plugin/` directory so the user-scope file does not depend - * on env-var expansion (Codex only injects `CLAUDE_PLUGIN_ROOT` for - * plugin-scope hooks). + * on env-var expansion (only Claude Code actually injects + * `CLAUDE_PLUGIN_ROOT` for plugin-scope hooks — the token is reused here + * purely as an internal placeholder for "the bundled plugin/ dir"). * * Identification on re-install: every command we write contains the * resolved `/scripts/` prefix, so subsequent installs can diff --git a/src/cli/connect/droid.ts b/src/cli/connect/droid.ts index 92ae69edd6..aea4c0fb4f 100644 --- a/src/cli/connect/droid.ts +++ b/src/cli/connect/droid.ts @@ -1,6 +1,15 @@ +import { existsSync, mkdirSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; +import * as p from "@clack/prompts"; import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; +import type { ConnectOptions, ConnectResult } from "./types.js"; +import { + buildMergedHooks, + findPluginRoot, + type HookManifest, +} from "./codex-hooks.js"; +import { backupFile, logBackup, logInstalled, readJsonSafe, writeJsonAtomic } from "./util.js"; // Factory.ai's Droid CLI stores MCP server config at ~/.factory/mcp.json // with the canonical `mcpServers` wrapper. Project-scoped overrides live @@ -8,14 +17,75 @@ import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; // ("stdio" | "http") and `disabled` boolean — agentmemory's stdio block // works against the same shape without needing the explicit type tag. // Source: docs.factory.ai/cli/configuration/mcp +// +// Droid also ships a native, first-party hooks system (SessionStart, +// SessionEnd, UserPromptSubmit, PreToolUse, PostToolUse) configured via +// `~/.factory/hooks.json`, in the same `{ hooks: { : [{ matcher?, +// hooks: [{ type, command }] }] } }` shape Claude Code and Codex use — so +// `--with-hooks` reuses `buildMergedHooks` from codex-hooks.ts with the +// bundled `hooks.droid.json` manifest instead of writing a new merge +// strategy. Source: docs.factory.ai/cli/configuration/hooks-guide +const DROID_DIR = join(homedir(), ".factory"); +const DROID_HOOKS = join(DROID_DIR, "hooks.json"); + export const adapter = createJsonMcpAdapter({ name: "droid", displayName: "Droid (Factory.ai)", - detectDir: join(homedir(), ".factory"), - configPath: join(homedir(), ".factory", "mcp.json"), + detectDir: DROID_DIR, + configPath: join(DROID_DIR, "mcp.json"), docs: "https://github.com/rohitg00/agentmemory#other-agents", protocolNote: - "→ Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers.", + "→ Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers. Pass --with-hooks to also install the native ~/.factory/hooks.json auto-capture hooks.", // Droid requires `type` per the documented schema. stdio for npx-spawned shim. extraEntryFields: { type: "stdio" }, + installHooks: installDroidHooks, }); + +/** + * Merge the bundled `plugin/hooks/hooks.droid.json` into + * `~/.factory/hooks.json`. Same idempotent merge/strip-by-script-path + * behavior as the Codex and Claude Code hook installers: re-running keeps + * user-authored hook entries and only replaces the ones agentmemory owns. + */ +function installDroidHooks(opts: ConnectOptions): ConnectResult { + let pluginRoot: string; + try { + pluginRoot = findPluginRoot(); + } catch (err) { + return { + kind: "skipped", + reason: err instanceof Error ? err.message : String(err), + }; + } + + const existing = readJsonSafe(DROID_HOOKS); + const merged = buildMergedHooks(existing, pluginRoot, "hooks.droid.json"); + + if (opts.dryRun) { + p.log.info( + `[dry-run] Would ${existing ? "merge" : "create"} ${DROID_HOOKS} with ${Object.keys(merged.hooks).length} event(s)`, + ); + return { kind: "installed", mutatedPath: DROID_HOOKS }; + } + + let backupPath: string | undefined; + if (existsSync(DROID_HOOKS)) { + backupPath = backupFile(DROID_HOOKS, "droid-hooks", "json"); + logBackup(backupPath); + } else { + mkdirSync(DROID_DIR, { recursive: true }); + } + + writeJsonAtomic(DROID_HOOKS, merged); + + logInstalled("Droid hooks", DROID_HOOKS); + p.log.info( + "User-scope hooks reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect droid --with-hooks` after upgrading agentmemory to refresh them.", + ); + + return { + kind: "installed", + mutatedPath: DROID_HOOKS, + ...(backupPath !== undefined && { backupPath }), + }; +} diff --git a/src/cli/connect/json-mcp-adapter.ts b/src/cli/connect/json-mcp-adapter.ts index 35998e0dc5..e79cfea51a 100644 --- a/src/cli/connect/json-mcp-adapter.ts +++ b/src/cli/connect/json-mcp-adapter.ts @@ -29,6 +29,12 @@ export type JsonMcpAdapterConfig = { // Extra fields merged into the agentmemory entry. Droid requires // type: "stdio"; other hosts ignore unknown fields. extraEntryFields?: Record; + // Invoked when `--with-hooks` is passed, independent of whether the MCP + // entry was freshly installed or already wired (mirrors the Claude Code / + // Codex adapters, issue #508 pattern) — hosts that ship a native hook + // config alongside MCP (e.g. Droid's `~/.factory/hooks.json`) pass this + // to install/refresh their hook manifest. + installHooks?: (opts: ConnectOptions) => ConnectResult; }; type McpEntry = typeof AGENTMEMORY_MCP_BLOCK; @@ -69,6 +75,14 @@ export function createJsonMcpAdapter( const alreadyHas = entryMatches(servers["agentmemory"]); if (alreadyHas && !opts.force) { logAlreadyWired(config.displayName, config.configPath); + if (opts.withHooks && config.installHooks) { + const hookResult = config.installHooks(opts); + if (hookResult.kind === "skipped") { + p.log.warn( + `${config.displayName} hooks skipped: ${hookResult.reason}.`, + ); + } + } return { kind: "already-wired", mutatedPath: config.configPath }; } @@ -76,6 +90,7 @@ export function createJsonMcpAdapter( p.log.info( `[dry-run] Would ${alreadyHas ? "overwrite" : "add"} ${wrapperKey}.agentmemory in ${config.configPath}`, ); + if (opts.withHooks && config.installHooks) config.installHooks(opts); return { kind: "installed", mutatedPath: config.configPath }; } @@ -106,6 +121,16 @@ export function createJsonMcpAdapter( } logInstalled(config.displayName, config.configPath); + + if (opts.withHooks && config.installHooks) { + const hookResult = config.installHooks(opts); + if (hookResult.kind === "skipped") { + p.log.warn( + `${config.displayName} hooks skipped: ${hookResult.reason}. MCP wiring still applied.`, + ); + } + } + return { kind: "installed", mutatedPath: config.configPath, diff --git a/src/cli/connect/types.ts b/src/cli/connect/types.ts index 169dde1382..f0bc04b83b 100644 --- a/src/cli/connect/types.ts +++ b/src/cli/connect/types.ts @@ -2,10 +2,11 @@ export type ConnectOptions = { dryRun: boolean; force: boolean; /** - * When true, the Codex adapter additionally writes a global - * `~/.codex/hooks.json` block referencing absolute paths to bundled hook - * scripts. Workaround for openai/codex#16430, which prevents plugin-local - * hooks from dispatching on Codex Desktop. No-op for other adapters. + * When true, adapters that ship a native hook config alongside MCP + * additionally write it: Codex (`~/.codex/hooks.json`, workaround for + * openai/codex#16430), Claude Code (`~/.claude/settings.json`, workaround + * for #508), and Droid (`~/.factory/hooks.json`, its native hooks + * config). No-op for adapters without a hooks installer. */ withHooks?: boolean; }; diff --git a/test/connect-new-agents.test.ts b/test/connect-new-agents.test.ts index 9ac4485ab5..3c16a0b0c6 100644 --- a/test/connect-new-agents.test.ts +++ b/test/connect-new-agents.test.ts @@ -14,13 +14,20 @@ function freshHome(): string { describe("connect: Qwen Code", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -52,13 +59,20 @@ describe("connect: Qwen Code", () => { describe("connect: Antigravity", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -85,13 +99,20 @@ describe("connect: Antigravity", () => { describe("connect: Kiro", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -117,13 +138,20 @@ describe("connect: Kiro", () => { describe("connect: Warp", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -152,13 +180,20 @@ describe("connect: Warp", () => { describe("connect: Cline", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -184,13 +219,20 @@ describe("connect: Cline", () => { describe("connect: Droid (Factory.ai)", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -213,18 +255,68 @@ describe("connect: Droid (Factory.ai)", () => { // Droid requires `type` per its documented schema expect(cfg.mcpServers.agentmemory.type).toBe("stdio"); }); + + it("--with-hooks additionally writes ~/.factory/hooks.json with Droid's native events", async () => { + mkdirSync(join(home, ".factory"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/droid.js"); + const result = await adapter.install({ + dryRun: false, + force: false, + withHooks: true, + }); + expect(result.kind).toBe("installed"); + const hooksPath = join(home, ".factory", "hooks.json"); + expect(existsSync(hooksPath)).toBe(true); + const hooks = JSON.parse(readFileSync(hooksPath, "utf-8")); + for (const event of [ + "SessionStart", + "UserPromptSubmit", + "PreToolUse", + "PostToolUse", + "SessionEnd", + ]) { + expect(Object.keys(hooks.hooks)).toContain(event); + } + }); + + it("without --with-hooks, does not write ~/.factory/hooks.json", async () => { + mkdirSync(join(home, ".factory"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/droid.js"); + await adapter.install({ dryRun: false, force: false }); + expect(existsSync(join(home, ".factory", "hooks.json"))).toBe(false); + }); + + it("re-running install with --with-hooks on an already-wired MCP config still refreshes hooks.json", async () => { + mkdirSync(join(home, ".factory"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/droid.js"); + await adapter.install({ dryRun: false, force: false }); + const result = await adapter.install({ + dryRun: false, + force: false, + withHooks: true, + }); + expect(result.kind).toBe("already-wired"); + expect(existsSync(join(home, ".factory", "hooks.json"))).toBe(true); + }); }); describe("connect: Zed", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); @@ -251,13 +343,20 @@ describe("connect: Zed", () => { describe("connect: Continue.dev", () => { let home: string; const ORIG = process.env["HOME"]; + const ORIG_USERPROFILE = process.env["USERPROFILE"]; beforeEach(() => { home = freshHome(); vi.resetModules(); process.env["HOME"] = home; + // os.homedir() on win32 reads USERPROFILE, not HOME — without this, + // adapter.detect()/install() resolve the real user's home directory + // instead of the isolated temp one. + process.env["USERPROFILE"] = home; }); afterEach(() => { process.env["HOME"] = ORIG; + if (ORIG_USERPROFILE === undefined) delete process.env["USERPROFILE"]; + else process.env["USERPROFILE"] = ORIG_USERPROFILE; rmSync(home, { recursive: true, force: true }); }); diff --git a/test/droid-connect-hooks.test.ts b/test/droid-connect-hooks.test.ts new file mode 100644 index 0000000000..60d64e0407 --- /dev/null +++ b/test/droid-connect-hooks.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from "vitest"; +import { resolve } from "node:path"; +import { + buildMergedHooks, + findPluginRoot, + type HookManifest, +} from "../src/cli/connect/codex-hooks.js"; + +const PLUGIN_ROOT = resolve(__dirname, "..", "plugin"); + +describe("buildMergedHooks (Droid manifest)", () => { + it("rewrites ${CLAUDE_PLUGIN_ROOT} to absolute pluginRoot in every command", () => { + const merged = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); + for (const entries of Object.values(merged.hooks)) { + for (const entry of entries) { + for (const handler of entry.hooks) { + expect(handler.command).not.toContain("${CLAUDE_PLUGIN_ROOT}"); + expect(handler.command).toContain(`${PLUGIN_ROOT}/scripts/`); + } + } + } + }); + + it("includes Droid's five documented lifecycle events", () => { + const merged = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); + for (const event of [ + "SessionStart", + "UserPromptSubmit", + "PreToolUse", + "PostToolUse", + "SessionEnd", + ]) { + expect(Object.keys(merged.hooks)).toContain(event); + } + // Droid does not document PreCompact/Stop/Subagent* hooks — the + // Claude-only events must not leak into the Droid manifest. + expect(Object.keys(merged.hooks)).not.toContain("PreCompact"); + expect(Object.keys(merged.hooks)).not.toContain("Stop"); + }); + + it("preserves the PreToolUse matcher", () => { + const merged = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); + const preToolUse = merged.hooks["PreToolUse"]; + expect(preToolUse).toBeDefined(); + expect(preToolUse![0]!.matcher).toBe("Edit|Write|Read|Glob|Grep"); + }); + + it("appends to existing user hooks without dropping them", () => { + const existing: HookManifest = { + hooks: { + SessionStart: [ + { hooks: [{ type: "command", command: "echo user-custom" }] }, + ], + }, + }; + const merged = buildMergedHooks(existing, findPluginRoot(), "hooks.droid.json"); + const sessionStart = merged.hooks["SessionStart"]!; + expect( + sessionStart.some((e) => e.hooks.some((h) => h.command === "echo user-custom")), + ).toBe(true); + expect( + sessionStart.some((e) => + e.hooks.some((h) => h.command.includes("session-start.mjs")), + ), + ).toBe(true); + }); + + it("re-install is idempotent (no duplicate agentmemory entries)", () => { + const first = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); + const second = buildMergedHooks(first, findPluginRoot(), "hooks.droid.json"); + for (const event of Object.keys(first.hooks)) { + expect(second.hooks[event]!.length).toBe(first.hooks[event]!.length); + } + }); +}); From 13811786c1c444468c953a89506574df7e286edd Mon Sep 17 00:00:00 2001 From: Bertho Joris Date: Fri, 31 Jul 2026 13:55:02 +0700 Subject: [PATCH 2/5] docs: changelog entry + regenerate agentmemory-agents skill reference for Droid hooks CHANGELOG [Unreleased] entry for the new --with-hooks path, and npm run skills:gen to sync the auto-generated agents table (pulled from src/cli/connect/index.ts protocolNote) so it reflects Droid's updated hooks capability. tools/rest/config/hooks reference docs showed as stale too but diffed empty (pre-existing line-ending-only drift on this checkout) so left untouched. Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 4 ++++ plugin/skills/agentmemory-agents/REFERENCE.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24a1722e88..4d25db5338 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Added + +- **Native hooks adapter for Droid (Factory.ai)**. `agentmemory connect droid --with-hooks` now also merges the bundled `hooks.droid.json` manifest into Droid's native `~/.factory/hooks.json` (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, SessionEnd), reusing the same idempotent merge/re-install logic already backing the Codex and Claude Code hook installers. `createJsonMcpAdapter` gained an optional `installHooks` hook so other JSON-MCP-shaped adapters can opt into the same pattern later. + ## [0.9.28] — 2026-07-19 Patch release: hardens the hook runner against malformed payloads and closes a cross-agent context leak. No breaking changes; drop-in upgrade. diff --git a/plugin/skills/agentmemory-agents/REFERENCE.md b/plugin/skills/agentmemory-agents/REFERENCE.md index d1d829506d..a0ec69ca19 100644 --- a/plugin/skills/agentmemory-agents/REFERENCE.md +++ b/plugin/skills/agentmemory-agents/REFERENCE.md @@ -14,7 +14,7 @@ Generated from `src/cli/connect/index.ts`. Do not edit the block below by hand; | Continue | `continue` | Using MCP via ~/.continue/config.yaml (preferred) or config.json (legacy, only when no yaml). | | GitHub Copilot CLI | `copilot-cli` | Using MCP. Install the plugin too for full hooks/skills coverage. | | Cursor | `cursor` | Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath. | -| Droid (Factory.ai) | `droid` | Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers. | +| Droid (Factory.ai) | `droid` | Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers. Pass --with-hooks to also install the native ~/.factory/hooks.json auto-capture hooks. | | Gemini CLI | `gemini-cli` | Using MCP (the only protocol Gemini CLI speaks). Memory bridge runs at :3111 underneath. | | Hermes Agent | `hermes` | Using MCP. Hooks are also available, see https://github.com/rohitg00/agentmemory/tree/main/integrations/hermes. | | Kiro | `kiro` | Using MCP via ~/.kiro/settings/mcp.json (user-level). Workspace overrides live in .kiro/settings/mcp.json. | From d624e146b2328c35efcb1770d87e77aed95d6d39 Mon Sep 17 00:00:00 2001 From: Bertho Joris Date: Fri, 31 Jul 2026 15:01:32 +0700 Subject: [PATCH 3/5] fix(cli): surface skipped hook results in dry-run branch, tighten Droid hook tests - json-mcp-adapter: capture and warn on skipped hook results in the dry-run branch (consistent with already-wired and post-install branches) - droid-connect-hooks test: assert exact five-event set instead of presence-only plus selective absence checks - droid-connect-hooks test: use deep equality (toEqual) for idempotency check instead of per-event length comparison Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/cli/connect/json-mcp-adapter.ts | 9 ++++++++- test/droid-connect-hooks.test.ts | 21 ++++++++------------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/cli/connect/json-mcp-adapter.ts b/src/cli/connect/json-mcp-adapter.ts index e79cfea51a..9966e29761 100644 --- a/src/cli/connect/json-mcp-adapter.ts +++ b/src/cli/connect/json-mcp-adapter.ts @@ -90,7 +90,14 @@ export function createJsonMcpAdapter( p.log.info( `[dry-run] Would ${alreadyHas ? "overwrite" : "add"} ${wrapperKey}.agentmemory in ${config.configPath}`, ); - if (opts.withHooks && config.installHooks) config.installHooks(opts); + if (opts.withHooks && config.installHooks) { + const hookResult = config.installHooks(opts); + if (hookResult.kind === "skipped") { + p.log.warn( + `${config.displayName} hooks skipped: ${hookResult.reason}.`, + ); + } + } return { kind: "installed", mutatedPath: config.configPath }; } diff --git a/test/droid-connect-hooks.test.ts b/test/droid-connect-hooks.test.ts index 60d64e0407..9bf006b4d0 100644 --- a/test/droid-connect-hooks.test.ts +++ b/test/droid-connect-hooks.test.ts @@ -21,21 +21,18 @@ describe("buildMergedHooks (Droid manifest)", () => { } }); - it("includes Droid's five documented lifecycle events", () => { + it("includes Droid's five documented lifecycle events (and nothing else)", () => { const merged = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); - for (const event of [ + const expectedEvents = [ "SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "SessionEnd", - ]) { - expect(Object.keys(merged.hooks)).toContain(event); - } - // Droid does not document PreCompact/Stop/Subagent* hooks — the - // Claude-only events must not leak into the Droid manifest. - expect(Object.keys(merged.hooks)).not.toContain("PreCompact"); - expect(Object.keys(merged.hooks)).not.toContain("Stop"); + ]; + expect(Object.keys(merged.hooks).sort()).toEqual( + [...expectedEvents].sort(), + ); }); it("preserves the PreToolUse matcher", () => { @@ -65,11 +62,9 @@ describe("buildMergedHooks (Droid manifest)", () => { ).toBe(true); }); - it("re-install is idempotent (no duplicate agentmemory entries)", () => { + it("re-install is idempotent (produces identical manifest)", () => { const first = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); const second = buildMergedHooks(first, findPluginRoot(), "hooks.droid.json"); - for (const event of Object.keys(first.hooks)) { - expect(second.hooks[event]!.length).toBe(first.hooks[event]!.length); - } + expect(second).toEqual(first); }); }); From 072dab98cacedf3ef388325eb73bc385898f448e Mon Sep 17 00:00:00 2001 From: Bertho Joris Date: Sun, 2 Aug 2026 17:45:07 +0700 Subject: [PATCH 4/5] fix(cli): use Droid Create tool in PreToolUse matcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Droid has no Write tool — file creation is Create — so the Claude-era matcher blocked enrichment on new files. Align the manifest and test. Co-authored-by: Cursor --- plugin/hooks/hooks.droid.json | 2 +- test/droid-connect-hooks.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/hooks/hooks.droid.json b/plugin/hooks/hooks.droid.json index ff38349593..d6ea5d40bc 100644 --- a/plugin/hooks/hooks.droid.json +++ b/plugin/hooks/hooks.droid.json @@ -22,7 +22,7 @@ ], "PreToolUse": [ { - "matcher": "Edit|Write|Read|Glob|Grep", + "matcher": "Edit|Create|Read|Glob|Grep", "hooks": [ { "type": "command", diff --git a/test/droid-connect-hooks.test.ts b/test/droid-connect-hooks.test.ts index 9bf006b4d0..deac527b38 100644 --- a/test/droid-connect-hooks.test.ts +++ b/test/droid-connect-hooks.test.ts @@ -39,7 +39,7 @@ describe("buildMergedHooks (Droid manifest)", () => { const merged = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); const preToolUse = merged.hooks["PreToolUse"]; expect(preToolUse).toBeDefined(); - expect(preToolUse![0]!.matcher).toBe("Edit|Write|Read|Glob|Grep"); + expect(preToolUse![0]!.matcher).toBe("Edit|Create|Read|Glob|Grep"); }); it("appends to existing user hooks without dropping them", () => { From 7fa19603214a2e0d77dbbcd6cd7a52f43c56b348 Mon Sep 17 00:00:00 2001 From: Bertho Joris Date: Sun, 2 Aug 2026 17:49:37 +0700 Subject: [PATCH 5/5] docs: drop changelog entry and trim Droid README row Per review: remove the Unreleased CHANGELOG addition, and keep the Droid agents-table row short with a brief --with-hooks mention. Co-authored-by: Cursor --- CHANGELOG.md | 4 ---- README.md | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d25db5338..24a1722e88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] -### Added - -- **Native hooks adapter for Droid (Factory.ai)**. `agentmemory connect droid --with-hooks` now also merges the bundled `hooks.droid.json` manifest into Droid's native `~/.factory/hooks.json` (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, SessionEnd), reusing the same idempotent merge/re-install logic already backing the Codex and Claude Code hook installers. `createJsonMcpAdapter` gained an optional `installHooks` hook so other JSON-MCP-shaped adapters can opt into the same pattern later. - ## [0.9.28] — 2026-07-19 Patch release: hardens the hook runner against malformed payloads and closes a cross-agent context leak. No breaking changes; drop-in upgrade. diff --git a/README.md b/README.md index ff37d7aeb6..3df0603de8 100644 --- a/README.md +++ b/README.md @@ -677,7 +677,7 @@ The agentmemory entry is the **same MCP server block** across every host that us | **Cline (CLI)** | `~/.cline/mcp.json` | `agentmemory connect cline` writes the standard `mcpServers` block. VS Code extension users: paste the same block via Cline Settings → MCP Servers → Edit JSON. | | **Continue.dev** | `~/.continue/config.yaml` (preferred) or `config.json` (legacy) | `agentmemory connect continue` creates `config.yaml` from scratch when neither exists, or modifies existing `config.json`. **If you already have `config.yaml`** the adapter prints the exact block to paste under `mcpServers:` — it won't silently rewrite your yaml because preserving comments and anchors safely needs a YAML parser the package doesn't ship. Continue uses array form (not object) for `mcpServers`. | | **Zed** | `~/.config/zed/settings.json` | `agentmemory connect zed` writes under `context_servers` (Zed's key, NOT `mcpServers`). Remote MCP servers can be wired via `{"url": "..."}` instead. | -| **Droid (Factory.ai)** | `~/.factory/mcp.json` + `~/.factory/hooks.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `/.factory/mcp.json`. The `/mcp` slash command inside droid lists configured servers. Run `agentmemory connect droid --with-hooks` to also wire Droid's native hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, SessionEnd) into `~/.factory/hooks.json` for zero-effort auto-capture, same merge/re-install behavior as the Codex and Claude Code hook installers. | +| **Droid (Factory.ai)** | `~/.factory/mcp.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `/.factory/mcp.json`. Pass `--with-hooks` for native auto-capture. | | **Goose** | Goose MCP settings UI | Same `mcpServers` block — use `goose configure` → Add Extension → MCP. Direct YAML edit at `~/.config/goose/config.yaml` is supported but the schema uses `extensions:` + `cmd` (not `mcpServers:` + `command`). | | **Aider** | n/a | Talk to the REST API directly: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. | | **Any agent (32+)** | n/a | `npx skillkit install agentmemory` auto-detects the host and merges. |