diff --git a/README.md b/README.md index 48f4045cd6..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` | `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` | `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. | diff --git a/plugin/hooks/hooks.droid.json b/plugin/hooks/hooks.droid.json new file mode 100644 index 0000000000..d6ea5d40bc --- /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|Create|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/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. | 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..9966e29761 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,14 @@ export function createJsonMcpAdapter( p.log.info( `[dry-run] Would ${alreadyHas ? "overwrite" : "add"} ${wrapperKey}.agentmemory in ${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: "installed", mutatedPath: config.configPath }; } @@ -106,6 +128,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..deac527b38 --- /dev/null +++ b/test/droid-connect-hooks.test.ts @@ -0,0 +1,70 @@ +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 (and nothing else)", () => { + const merged = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); + const expectedEvents = [ + "SessionStart", + "UserPromptSubmit", + "PreToolUse", + "PostToolUse", + "SessionEnd", + ]; + expect(Object.keys(merged.hooks).sort()).toEqual( + [...expectedEvents].sort(), + ); + }); + + 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|Create|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 (produces identical manifest)", () => { + const first = buildMergedHooks(null, findPluginRoot(), "hooks.droid.json"); + const second = buildMergedHooks(first, findPluginRoot(), "hooks.droid.json"); + expect(second).toEqual(first); + }); +});