File size: 5,380 Bytes
d197cf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Hook installs must preserve discovery and execution across copied and linked layouts.
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { installPluginWithHookFallback } from "../cli/plugins-install-hook-fallback.js";
import { readConfigFileSnapshot } from "../config/config.js";
import { loadConfigForInstall } from "../plugins/install-config.js";
import {
  createOpenClawTestState,
  type OpenClawTestState,
} from "../test-utils/openclaw-test-state.js";
import { pinConfigDir } from "../utils.js";
import { readHookInstalls } from "./installs.js";
import {
  clearInternalHooks,
  createInternalHookEvent,
  setInternalHooksEnabled,
  triggerInternalHook,
} from "./internal-hooks.js";
import { prepareInternalHooks } from "./loader.js";
import { loadWorkspaceHookEntries } from "./workspace.js";

async function writeHook(hookDir: string, name: string): Promise<void> {
  await fs.mkdir(hookDir, { recursive: true });
  await fs.writeFile(
    path.join(hookDir, "HOOK.md"),
    [
      "---",
      `name: ${name}`,
      'description: "Test hook"',
      'metadata: {"openclaw":{"events":["command:new"]}}',
      "---",
      "",
    ].join("\n"),
    "utf-8",
  );
  await fs.writeFile(
    path.join(hookDir, "handler.js"),
    `export default async function(event) { event.messages.push(${JSON.stringify(name)}); }\n`,
    "utf-8",
  );
}

describe.each([
  { mode: "copied", link: false },
  { mode: "linked", link: true },
])("hooks install ($mode)", ({ link }) => {
  let state: OpenClawTestState;

  beforeEach(async () => {
    state = await createOpenClawTestState({ label: "hooks-install", layout: "split" });
    pinConfigDir();
    clearInternalHooks();
    await state.writeConfig({
      agents: { defaults: { workspace: state.workspaceDir } },
      plugins: { enabled: false },
    });
  });

  afterEach(async () => {
    try {
      const disabled = await prepareInternalHooks(
        { hooks: { internal: { enabled: false } } },
        state.workspaceDir,
      );
      disabled.commit();
      clearInternalHooks();
      setInternalHooksEnabled(true);
    } finally {
      await state.cleanup();
      pinConfigDir();
    }
  });

  it.each([
    { layout: "single hook", hookPath: ".", hookPackId: "hello-hook" },
    { layout: "conventional pack", hookPath: "./hooks/hello-hook", hookPackId: "hello-hooks" },
    { layout: "direct-child pack", hookPath: "./hello-hook", hookPackId: "hello-hooks" },
  ])(
    "discovers and triggers only installed hooks from a $layout",
    async ({ hookPath, hookPackId }) => {
      const sourceDir = state.path("sources", "hook-pack");
      await writeHook(path.resolve(sourceDir, hookPath), "hello-hook");
      await writeHook(state.path("sources", "adjacent-hook"), "adjacent-hook");
      if (hookPath !== ".") {
        await fs.writeFile(
          path.join(sourceDir, "package.json"),
          JSON.stringify({
            name: "@acme/hello-hooks",
            version: "0.0.0",
            openclaw: { hooks: [hookPath] },
          }),
          "utf-8",
        );
        // A package manifest selects its hooks; neither root nor nested siblings are implicit hooks.
        await writeHook(path.join(sourceDir, "unlisted-root"), "unlisted-root");
        await writeHook(path.join(sourceDir, "hooks", "unlisted-nested"), "unlisted-nested");
      }

      const snapshot = await loadConfigForInstall({
        rawSpec: sourceDir,
      });
      const installResult = await installPluginWithHookFallback({
        request: { source: "local", path: sourceDir, mode: "install", link },
        snapshot,
        safetyOverrides: { config: snapshot.config },
      });
      expect(installResult).toEqual({ ok: true });

      const installed = await readConfigFileSnapshot();
      expect(installed.valid).toBe(true);
      expect(installed.config.hooks?.internal).toMatchObject({
        enabled: true,
        entries: { "hello-hook": { enabled: true } },
      });
      expect(installed.config.hooks?.internal?.load?.extraDirs ?? []).toEqual(
        link ? [sourceDir] : [],
      );
      const installPath = link ? sourceDir : state.statePath("hooks", hookPackId);
      expect(readHookInstalls()).toEqual({
        [hookPackId]: expect.objectContaining({
          source: "path",
          sourcePath: sourceDir,
          installPath,
          hooks: ["hello-hook"],
        }),
      });
      await expect(
        fs.readFile(path.resolve(installPath, hookPath, "handler.js"), "utf-8"),
      ).resolves.toContain("hello-hook");

      const options = { bundledHooksDir: state.path("bundled-none") };
      const discovered = loadWorkspaceHookEntries(state.workspaceDir, {
        ...options,
        config: installed.config,
      });
      const prepared = await prepareInternalHooks(installed.config, state.workspaceDir, options);
      prepared.commit();
      const event = createInternalHookEvent("command", "new", "test-session");
      await triggerInternalHook(event);
      expect({
        discovered: discovered.map((entry) => entry.hook.name).toSorted(),
        loaded: prepared.loadedCount,
        messages: event.messages.toSorted(),
      }).toEqual({
        discovered: ["hello-hook"],
        loaded: 1,
        messages: ["hello-hook"],
      });
    },
  );
});