-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathopencode-plugin-shim.test.ts
More file actions
498 lines (447 loc) · 21.5 KB
/
Copy pathopencode-plugin-shim.test.ts
File metadata and controls
498 lines (447 loc) · 21.5 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
/**
* Tests for the generated OpenCode plugin shim — the bridge between the
* opencode plugin runtime and the failproofai binary. Exercises:
* • plugin event → binary stdin translation
* • binary response → plugin action translation (throw / SDK call)
* • spawnSync options (timeout, encoding, cwd)
* • hook key registration completeness
*
* The shim source is generated by `opencode.writeHookEntries(...)` so we
* write a fresh copy into a tempdir and dynamic-import it. spawnSync is
* stubbed via process.argv0 / process.execPath redirection: we instead
* mock node:child_process.spawnSync at the module level by monkey-patching
* the import after dynamic-import is impossible, so we use a different
* approach: load the shim file's source, replace `node:child_process` with
* an injected stub, and eval. This keeps the test fully in-memory.
*/
// @vitest-environment node
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { opencode } from "../../src/hooks/integrations";
interface SpawnCall {
cmd: string;
args: string[];
opts: { input?: string; encoding?: string; timeout?: number; cwd?: string };
}
interface SpawnResult {
status: number | null;
stdout: string;
stderr: string;
}
interface PluginHooks {
event?: (input: { event: { type: string; properties?: Record<string, unknown> } }) => Promise<void>;
"tool.execute.before"?: (input: { tool: string; sessionID: string; callID: string }, output: { args: Record<string, unknown> }) => Promise<void>;
"tool.execute.after"?: (input: { tool: string; sessionID: string; callID: string; args: Record<string, unknown> }, output: { title: string; output: string; metadata: Record<string, unknown> }) => Promise<void>;
"permission.ask"?: (input: Record<string, unknown>, output: { status: string }) => Promise<void>;
}
type ShimEntry = (ctx: { client: unknown; directory: string }) => Promise<PluginHooks>;
/**
* Load the shim from a tempdir, monkey-patching its `node:child_process`
* import so spawnSync is captured into `calls` and returns the next
* canned SpawnResult from `responses`.
*/
async function loadShim(opts: { scope: "user" | "project"; binaryPath: string; calls: SpawnCall[]; responses: SpawnResult[] }): Promise<{
plugin: ShimEntry;
cleanup: () => void;
pluginPath: string;
}> {
const dir = mkdtempSync(join(tmpdir(), "fp-opencode-shim-"));
const cwd = process.cwd();
process.chdir(dir);
try {
opencode.writeHookEntries({}, opts.binaryPath, opts.scope);
} finally {
process.chdir(cwd);
}
const pluginPath = opts.scope === "project"
? join(dir, ".opencode", "plugins", "failproofai.mjs")
: join(dir, ".opencode", "plugins", "failproofai.mjs"); // we still wrote project-side for user-scope tests below by chdir-ing
// For user scope we re-derive the actual path via the integration:
const realPath = opts.scope === "user"
? opencode.getSettingsPath("user").replace(/opencode\.json$/, "plugins/failproofai.mjs")
: pluginPath;
// For the test, we always read the project-scope shim from `dir` since
// that's what we just wrote (writeHookEntries with user-scope writes to
// the real ~/.config — we don't want to touch that). Instead, render
// the user-scope shim source directly via a fresh writeHookEntries call.
const shimSource = opts.scope === "project"
? readFileSync(pluginPath, "utf8")
: (() => {
// Re-render via project-scope but post-process to flip USE_NPX=false
// and inject the absolute binary path — keeps the test fully local.
const projectSrc = readFileSync(pluginPath, "utf8");
return projectSrc
.replace("USE_NPX = true", "USE_NPX = false")
.replace('FAILPROOFAI_BIN = ""', `FAILPROOFAI_BIN = ${JSON.stringify(opts.binaryPath)}`);
})();
// Replace the spawnSync import with our stub. The shim imports it as
// `import { spawnSync } from "node:child_process"`. We rewrite that line
// to read from a global injected by this test.
const stubbed = shimSource.replace(
'import { spawnSync } from "node:child_process";',
`const spawnSync = globalThis.__fp_test_spawnSync;`,
);
// Pre-set the stub before importing.
(globalThis as unknown as Record<string, unknown>).__fp_test_spawnSync = (cmd: string, args: string[], optsArg: SpawnCall["opts"]): SpawnResult => {
opts.calls.push({ cmd, args, opts: optsArg });
const r = opts.responses.shift();
if (!r) return { status: 0, stdout: "", stderr: "" };
return r;
};
// Write a sibling .mjs we can dynamic-import without touching the original.
const importablePath = join(dir, ".opencode", "plugins", "failproofai.test.mjs");
const fs = await import("node:fs");
fs.writeFileSync(importablePath, stubbed, "utf8");
const mod = await import(importablePath);
return {
plugin: mod.default as ShimEntry,
pluginPath: realPath,
cleanup: () => {
delete (globalThis as unknown as Record<string, unknown>).__fp_test_spawnSync;
rmSync(dir, { recursive: true, force: true });
},
};
}
function fakeClient() {
return { session: { prompt: vi.fn().mockResolvedValue(undefined) } };
}
describe("OpenCode plugin shim — translation of plugin events to binary stdin", () => {
let calls: SpawnCall[];
let responses: SpawnResult[];
let cleanup: () => void = () => {};
beforeEach(() => {
calls = [];
responses = [];
});
afterEach(() => cleanup());
async function setup() {
const r = await loadShim({ scope: "project", binaryPath: "/abs/bin/failproofai", calls, responses });
cleanup = r.cleanup;
return r;
}
it("tool.execute.before invokes spawnSync with --hook PreToolUse --cli opencode and the right stdin", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks["tool.execute.before"]!({ tool: "bash", sessionID: "ses_1", callID: "c1" }, { args: { command: "ls" } });
expect(calls).toHaveLength(1);
expect(calls[0].args).toEqual(["-y", "failproofai", "--hook", "PreToolUse", "--cli", "opencode"]);
const stdin = JSON.parse(calls[0].opts.input!);
// Shim canonicalizes lowercase opencode tool IDs (`bash`) to Claude
// PascalCase (`Bash`) before the JSON crosses to the binary, so builtin
// policies' case-sensitive `toolNames: ["Bash"]` filter fires.
expect(stdin.tool_name).toBe("Bash");
expect(stdin.tool_input).toEqual({ command: "ls" });
expect(stdin.session_id).toBe("ses_1");
expect(stdin.cwd).toBe("/repo");
expect(stdin.hook_event_name).toBe("PreToolUse");
});
it("tool.execute.before passes through unknown tool IDs unchanged", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks["tool.execute.before"]!(
{ tool: "mcp_github_create_issue", sessionID: "ses_1", callID: "c1" },
{ args: { title: "x" } },
);
const stdin = JSON.parse(calls[0].opts.input!);
// Unknown tools (MCP `mcp_*`, third-party extensions) must pass through
// unchanged so non-builtin custom policies that match by raw name still work.
expect(stdin.tool_name).toBe("mcp_github_create_issue");
});
it("tool.execute.before canonicalizes every OPENCODE_TOOL_MAP entry", async () => {
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
const cases: Array<[string, string]> = [
["bash", "Bash"],
["read", "Read"],
["write", "Write"],
["edit", "Edit"],
["apply_patch", "Edit"],
["glob", "Glob"],
["grep", "Grep"],
["list", "LS"],
["webfetch", "WebFetch"],
["websearch", "WebSearch"],
["todowrite", "TodoWrite"],
["todoread", "TodoRead"],
];
for (const [raw, canonical] of cases) {
responses.push({ status: 0, stdout: "", stderr: "" });
await hooks["tool.execute.before"]!({ tool: raw, sessionID: "ses_1", callID: "c1" }, { args: {} });
const stdin = JSON.parse(calls[calls.length - 1].opts.input!);
expect(stdin.tool_name).toBe(canonical);
}
});
it("tool.execute.after uses input.args (not output.args) and includes tool_response", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks["tool.execute.after"]!(
{ tool: "bash", sessionID: "ses_1", callID: "c1", args: { command: "ls" } },
{ title: "ok", output: "file1\nfile2", metadata: { exit: 0 } },
);
expect(calls).toHaveLength(1);
expect(calls[0].args).toContain("PostToolUse");
const stdin = JSON.parse(calls[0].opts.input!);
expect(stdin.tool_input).toEqual({ command: "ls" });
expect(stdin.tool_response).toEqual({ title: "ok", output: "file1\nfile2", metadata: { exit: 0 } });
});
it("permission.ask invokes --hook PermissionRequest", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
const out = { status: "ask" };
await hooks["permission.ask"]!({ tool: "bash", sessionID: "ses_1" }, out);
expect(calls).toHaveLength(1);
expect(calls[0].args).toContain("PermissionRequest");
});
it("event session.created → SessionStart", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks.event!({ event: { type: "session.created", properties: { sessionID: "ses_1" } } });
expect(calls[0].args).toContain("SessionStart");
});
it("event session.deleted → SessionEnd", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks.event!({ event: { type: "session.deleted", properties: { sessionID: "ses_1" } } });
expect(calls[0].args).toContain("SessionEnd");
});
it("event session.idle → Stop", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } });
expect(calls[0].args).toContain("Stop");
});
it("event message.updated with role:user → UserPromptSubmit", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks.event!({ event: { type: "message.updated", properties: { info: { role: "user", sessionID: "ses_1" } } } });
expect(calls[0].args).toContain("UserPromptSubmit");
});
it("event message.updated with role:assistant is FILTERED OUT (no spawn)", async () => {
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks.event!({ event: { type: "message.updated", properties: { info: { role: "assistant", sessionID: "ses_1" } } } });
expect(calls).toHaveLength(0);
});
it("event with unknown type is a no-op", async () => {
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await hooks.event!({ event: { type: "lsp.updated", properties: {} } });
await hooks.event!({ event: { type: "command.executed", properties: {} } });
await hooks.event!({ event: { type: "server.instance.disposed", properties: { directory: "/repo" } } });
expect(calls).toHaveLength(0);
});
});
describe("OpenCode plugin shim — translation of binary response to plugin action", () => {
let calls: SpawnCall[];
let responses: SpawnResult[];
let cleanup: () => void = () => {};
beforeEach(() => {
calls = [];
responses = [];
});
afterEach(() => cleanup());
async function setup() {
const r = await loadShim({ scope: "project", binaryPath: "/abs/bin/failproofai", calls, responses });
cleanup = r.cleanup;
return r;
}
it("exit code 2 → tool.execute.before throws Error(stderr)", async () => {
responses.push({ status: 2, stdout: "", stderr: "MANDATORY: commit first" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await expect(
hooks["tool.execute.before"]!({ tool: "bash", sessionID: "s", callID: "c" }, { args: {} }),
).rejects.toThrow(/MANDATORY: commit first/);
});
it("hookSpecificOutput.permissionDecision=deny → throws with the reason", async () => {
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { permissionDecision: "deny", permissionDecisionReason: "Bad command" } }),
stderr: "",
});
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await expect(
hooks["tool.execute.before"]!({ tool: "bash", sessionID: "s", callID: "c" }, { args: {} }),
).rejects.toThrow(/Bad command/);
});
it("hookSpecificOutput.additionalContext → calls client.session.prompt and does NOT throw", async () => {
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { additionalContext: "Note: hello" } }),
stderr: "",
});
const client = fakeClient();
const { plugin } = await setup();
const hooks = await plugin({ client, directory: "/repo" });
await hooks["tool.execute.before"]!({ tool: "bash", sessionID: "ses_1", callID: "c" }, { args: {} });
// Allow the fire-and-forget Promise.resolve to flush.
await new Promise((r) => setImmediate(r));
expect(client.session.prompt).toHaveBeenCalledTimes(1);
const callArg = client.session.prompt.mock.calls[0][0];
expect(callArg.path.id).toBe("ses_1");
expect(callArg.body.parts[0]).toEqual({ type: "text", text: "Note: hello" });
});
it("SDK rejection on session.prompt is swallowed (fire-and-forget)", async () => {
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { additionalContext: "Note" } }),
stderr: "",
});
const client = { session: { prompt: vi.fn().mockRejectedValue(new Error("network")) } };
const { plugin } = await setup();
const hooks = await plugin({ client, directory: "/repo" });
await expect(
hooks["tool.execute.before"]!({ tool: "bash", sessionID: "ses_1", callID: "c" }, { args: {} }),
).resolves.toBeUndefined();
});
it("empty stdout + exit 0 → fail-open allow (no throw, no SDK call)", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const client = fakeClient();
const { plugin } = await setup();
const hooks = await plugin({ client, directory: "/repo" });
await hooks["tool.execute.before"]!({ tool: "bash", sessionID: "s", callID: "c" }, { args: {} });
expect(client.session.prompt).not.toHaveBeenCalled();
});
it("malformed JSON on stdout → fail-open allow", async () => {
responses.push({ status: 0, stdout: "not json", stderr: "" });
const client = fakeClient();
const { plugin } = await setup();
const hooks = await plugin({ client, directory: "/repo" });
await expect(
hooks["tool.execute.before"]!({ tool: "bash", sessionID: "s", callID: "c" }, { args: {} }),
).resolves.toBeUndefined();
expect(client.session.prompt).not.toHaveBeenCalled();
});
it("Codex-shape PermissionRequest deny → throws with decision.message", async () => {
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { decision: { behavior: "deny", message: "Codex denied" } } }),
stderr: "",
});
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await expect(
hooks["tool.execute.before"]!({ tool: "bash", sessionID: "s", callID: "c" }, { args: {} }),
).rejects.toThrow(/Codex denied/);
});
it("permission.ask: a deny mutates output.status to 'deny' (does NOT throw)", async () => {
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { permissionDecision: "deny", permissionDecisionReason: "X" } }),
stderr: "",
});
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
const out = { status: "ask" };
await hooks["permission.ask"]!({ tool: "bash", sessionID: "s" }, out);
expect(out.status).toBe("deny");
});
it("event session.idle + additionalContext → AWAITS client.session.prompt (Stop force-retry)", async () => {
// For Stop events the prompt is the only force-retry channel — it MUST
// land before the plugin handler returns or OpenCode tears down the
// plugin context. Verify by making session.prompt return a Promise that
// resolves on a tick we control: if the handler awaits, it won't return
// until we tick.
let resolvePrompt: () => void = () => {};
const promptPromise = new Promise<void>((res) => { resolvePrompt = res; });
const client = { session: { prompt: vi.fn().mockReturnValue(promptPromise) } };
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { additionalContext: "Run tests before stopping" } }),
stderr: "",
});
const { plugin } = await setup();
const hooks = await plugin({ client, directory: "/repo" });
// Fire the handler and observe that it does NOT resolve until prompt resolves.
let handlerSettled = false;
const handlerDone = (async () => {
await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } });
handlerSettled = true;
})();
// Yield to the microtask queue; the handler should still be pending.
await new Promise((r) => setImmediate(r));
expect(handlerSettled).toBe(false);
expect(client.session.prompt).toHaveBeenCalledTimes(1);
const arg = client.session.prompt.mock.calls[0][0] as { path: { id: string }; body: { parts: Array<{ type: string; text: string }> } };
expect(arg.path.id).toBe("ses_1");
expect(arg.body.parts[0]).toEqual({ type: "text", text: "Run tests before stopping" });
// Resolve the SDK call; the handler should now finish.
resolvePrompt();
await handlerDone;
expect(handlerSettled).toBe(true);
});
it("event session.idle + SDK rejection on prompt is swallowed (agent already exiting)", async () => {
responses.push({
status: 0,
stdout: JSON.stringify({ hookSpecificOutput: { additionalContext: "..." } }),
stderr: "",
});
const client = { session: { prompt: vi.fn().mockRejectedValue(new Error("network")) } };
const { plugin } = await setup();
const hooks = await plugin({ client, directory: "/repo" });
await expect(
hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } }),
).resolves.toBeUndefined();
});
it("event session.idle + exit 2 → still throws (back-compat with stale binaries)", async () => {
responses.push({ status: 2, stdout: "", stderr: "MANDATORY: commit before stopping" });
const { plugin } = await setup();
const hooks = await plugin({ client: fakeClient(), directory: "/repo" });
await expect(
hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } }),
).rejects.toThrow(/MANDATORY: commit before stopping/);
});
});
describe("OpenCode plugin shim — spawn options and registration", () => {
let calls: SpawnCall[];
let responses: SpawnResult[];
let cleanup: () => void = () => {};
beforeEach(() => {
calls = [];
responses = [];
});
afterEach(() => cleanup());
it("spawnSync includes timeout, encoding, and cwd", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const r = await loadShim({ scope: "project", binaryPath: "/abs/bin/failproofai", calls, responses });
cleanup = r.cleanup;
const hooks = await r.plugin({ client: fakeClient(), directory: "/some/cwd" });
await hooks["tool.execute.before"]!({ tool: "bash", sessionID: "s", callID: "c" }, { args: {} });
expect(calls[0].opts.timeout).toBe(60_000);
expect(calls[0].opts.encoding).toBe("utf8");
expect(calls[0].opts.cwd).toBe("/some/cwd");
});
it("registers exactly the expected hook keys", async () => {
responses.push({ status: 0, stdout: "", stderr: "" });
const r = await loadShim({ scope: "project", binaryPath: "/abs/bin/failproofai", calls, responses });
cleanup = r.cleanup;
const hooks = await r.plugin({ client: fakeClient(), directory: "/repo" });
expect(Object.keys(hooks).sort()).toEqual([
"event",
"permission.ask",
"tool.execute.after",
"tool.execute.before",
]);
});
it("the EVENTS map covers all bus events listed in the spec", async () => {
// Read the generated shim source and pull out the BUS_EVENT_MAP keys.
const r = await loadShim({ scope: "project", binaryPath: "/abs/bin/failproofai", calls, responses });
cleanup = r.cleanup;
const source = readFileSync(r.pluginPath, "utf8");
expect(source).toContain('"session.created"');
expect(source).toContain('"session.deleted"');
expect(source).toContain('"session.idle"');
expect(source).toContain('"message.updated"');
});
});