@agentic-sdlc-kit/mod-sdk 0.0.0-stage → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/dist/capabilities/analyzer.d.ts +13 -0
  3. package/dist/capabilities/analyzer.d.ts.map +1 -0
  4. package/dist/capabilities/analyzer.js +58 -0
  5. package/dist/capabilities/analyzer.js.map +1 -0
  6. package/dist/capabilities/index.d.ts +2 -0
  7. package/dist/capabilities/index.d.ts.map +1 -0
  8. package/dist/capabilities/index.js +3 -0
  9. package/dist/capabilities/index.js.map +1 -0
  10. package/dist/capabilities/manifest.d.ts +40 -0
  11. package/dist/capabilities/manifest.d.ts.map +1 -0
  12. package/dist/capabilities/manifest.js +35 -0
  13. package/dist/capabilities/manifest.js.map +1 -0
  14. package/dist/claude-code-shim.d.ts +22 -0
  15. package/dist/claude-code-shim.d.ts.map +1 -0
  16. package/dist/claude-code-shim.js +30 -0
  17. package/dist/claude-code-shim.js.map +1 -0
  18. package/dist/index.d.ts +5 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +14 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/middleware/compose.d.ts +3 -0
  23. package/dist/middleware/compose.d.ts.map +1 -0
  24. package/dist/middleware/compose.js +28 -0
  25. package/dist/middleware/compose.js.map +1 -0
  26. package/dist/middleware/index.d.ts +2 -0
  27. package/dist/middleware/index.d.ts.map +1 -0
  28. package/dist/middleware/index.js +3 -0
  29. package/dist/middleware/index.js.map +1 -0
  30. package/dist/testing/index.d.ts +2 -0
  31. package/dist/testing/index.d.ts.map +1 -0
  32. package/dist/testing/index.js +3 -0
  33. package/dist/testing/index.js.map +1 -0
  34. package/dist/testing/mock-runtime.d.ts +96 -0
  35. package/dist/testing/mock-runtime.d.ts.map +1 -0
  36. package/dist/testing/mock-runtime.js +379 -0
  37. package/dist/testing/mock-runtime.js.map +1 -0
  38. package/dist/types/events.d.ts +158 -0
  39. package/dist/types/events.d.ts.map +1 -0
  40. package/dist/types/events.js +35 -0
  41. package/dist/types/events.js.map +1 -0
  42. package/dist/types/index.d.ts +2 -0
  43. package/dist/types/index.d.ts.map +1 -0
  44. package/dist/types/index.js +3 -0
  45. package/dist/types/index.js.map +1 -0
  46. package/package.json +37 -3
  47. package/src/capabilities/analyzer.test.ts +77 -0
  48. package/src/capabilities/analyzer.ts +68 -0
  49. package/src/capabilities/index.ts +2 -0
  50. package/src/capabilities/manifest.ts +38 -0
  51. package/src/claude-code-shim.ts +43 -0
  52. package/src/index.ts +14 -0
  53. package/src/middleware/compose.test.ts +70 -0
  54. package/src/middleware/compose.ts +29 -0
  55. package/src/middleware/index.ts +2 -0
  56. package/src/testing/index.ts +2 -0
  57. package/src/testing/mock-runtime.test.ts +264 -0
  58. package/src/testing/mock-runtime.ts +452 -0
  59. package/src/types/events.ts +275 -0
  60. package/src/types/index.ts +2 -0
  61. package/README.md +0 -3
@@ -0,0 +1,77 @@
1
+ // packages/mod-sdk/src/capabilities/analyzer.test.ts
2
+ import { describe, expect, it } from 'vitest';
3
+ import { analyzeRegisterSource } from './analyzer.js';
4
+ import type { ModCapabilities } from './manifest.js';
5
+
6
+ const declared: ModCapabilities = {
7
+ id: 'test-mod',
8
+ version: '0.7.0',
9
+ hooks: ['tool.call', 'tool.check'],
10
+ apiAccess: ['ui.log', 'state.get'],
11
+ filesystemAccess: [],
12
+ networkAccess: false,
13
+ processExecution: false,
14
+ modifiesPrompts: false,
15
+ modifiesToolCalls: true,
16
+ modifiesModels: false,
17
+ learningAutonomyLevel: 'L0',
18
+ };
19
+
20
+ describe('analyzeRegisterSource', () => {
21
+ it('extracts declared hooks and api access from source', () => {
22
+ const source = `
23
+ export function register(on) {
24
+ on('tool.call', async ($, e, next) => {
25
+ $.ui.log('hi');
26
+ $.state.get('x');
27
+ return next(e);
28
+ });
29
+ on('tool.check', async ($, e, next) => next(e));
30
+ }
31
+ `;
32
+ const r = analyzeRegisterSource(source, declared);
33
+ expect(r.declaredHooks).toContain('tool.call');
34
+ expect(r.declaredHooks).toContain('tool.check');
35
+ expect(r.declaredApiAccess).toContain('ui.log');
36
+ expect(r.declaredApiAccess).toContain('state.get');
37
+ expect(r.mismatches).toEqual([]);
38
+ });
39
+
40
+ it('flags a hook used in source but not declared in manifest', () => {
41
+ const source = `
42
+ export function register(on) {
43
+ on('turn.step', async ($, e, next) => next(e));
44
+ }
45
+ `;
46
+ const r = analyzeRegisterSource(source, declared);
47
+ expect(r.mismatches).toContain(
48
+ "source registers hook 'turn.step' but manifest does not declare it",
49
+ );
50
+ });
51
+
52
+ it('flags an API used in source but not declared in manifest', () => {
53
+ const source = `
54
+ export function register(on) {
55
+ on('tool.call', async ($, e, next) => {
56
+ $.fs.read('/x');
57
+ return next(e);
58
+ });
59
+ }
60
+ `;
61
+ const r = analyzeRegisterSource(source, declared);
62
+ expect(r.mismatches.some((m) => m.includes('fs.read'))).toBe(true);
63
+ });
64
+
65
+ it('flags network access when manifest declares networkAccess=false', () => {
66
+ const source = `
67
+ export function register(on) {
68
+ on('tool.call', async ($, e, next) => {
69
+ await $.http.fetch('https://example.com');
70
+ return next(e);
71
+ });
72
+ }
73
+ `;
74
+ const r = analyzeRegisterSource(source, declared);
75
+ expect(r.mismatches.some((m) => m.includes('http.fetch'))).toBe(true);
76
+ });
77
+ });
@@ -0,0 +1,68 @@
1
+ // packages/mod-sdk/src/capabilities/analyzer.ts
2
+ //
3
+ // Static capability analyzer. Parses a Mod's register.ts source to extract
4
+ // declared events and API calls, then compares against the declared
5
+ // ModCapabilities manifest.
6
+ //
7
+ // This is a lightweight text-based analyzer; it does not load the module.
8
+ // It looks for `on('event.name', ...)` and `$.namespace.method(...)` calls.
9
+
10
+ import type { ModCapabilities } from './manifest.js';
11
+
12
+ export interface AnalysisResult {
13
+ declaredHooks: string[];
14
+ declaredApiAccess: string[];
15
+ mismatches: string[];
16
+ }
17
+
18
+ /**
19
+ * Analyze a register.ts source string for declared events and API calls.
20
+ * Returns the extracted surface and any mismatches against the declared
21
+ * capabilities.
22
+ */
23
+ export function analyzeRegisterSource(source: string, declared: ModCapabilities): AnalysisResult {
24
+ const declaredHooks = new Set<string>();
25
+ const declaredApiAccess = new Set<string>();
26
+
27
+ // Find on('event.name', ...) and on("event.name", ...) calls.
28
+ const onRegex = /\bon\(\s*['"]([a-z.]+)['"]/g;
29
+ let m: RegExpExecArray | null;
30
+ while ((m = onRegex.exec(source)) !== null) {
31
+ const ev = m[1];
32
+ if (ev) declaredHooks.add(ev);
33
+ }
34
+
35
+ // Find $.namespace.method( calls.
36
+ const apiRegex = /\$\.\s*([a-zA-Z]+)\.([a-zA-Z]+)/g;
37
+ while ((m = apiRegex.exec(source)) !== null) {
38
+ const ns = m[1];
39
+ const method = m[2];
40
+ if (ns && method) declaredApiAccess.add(`${ns}.${method}`);
41
+ }
42
+
43
+ // Check for mismatches.
44
+ const mismatches: string[] = [];
45
+ for (const h of declaredHooks) {
46
+ if (!declared.hooks.includes(h)) {
47
+ mismatches.push(`source registers hook '${h}' but manifest does not declare it`);
48
+ }
49
+ }
50
+ for (const a of declaredApiAccess) {
51
+ if (!declared.apiAccess.includes(a)) {
52
+ mismatches.push(`source uses API '${a}' but manifest does not declare it`);
53
+ }
54
+ }
55
+ // Check network/process usage.
56
+ if (declared.networkAccess === false && /\$\.http\.fetch/.test(source)) {
57
+ mismatches.push('source uses $.http.fetch but manifest declares networkAccess=false');
58
+ }
59
+ if (declared.processExecution === false && /\$\.process\.run/.test(source)) {
60
+ mismatches.push('source uses $.process.run but manifest declares processExecution=false');
61
+ }
62
+
63
+ return {
64
+ declaredHooks: Array.from(declaredHooks),
65
+ declaredApiAccess: Array.from(declaredApiAccess),
66
+ mismatches,
67
+ };
68
+ }
@@ -0,0 +1,2 @@
1
+ // packages/mod-sdk/src/capabilities/index.ts
2
+ export * from './manifest.js';
@@ -0,0 +1,38 @@
1
+ // packages/mod-sdk/src/capabilities/manifest.ts
2
+ //
3
+ // Mod capability manifest (RESEARCH.md §9). Every Mod declares its
4
+ // capabilities so the installer (M15) and validator can inspect them
5
+ // before enabling the Mod.
6
+ //
7
+ // This is the SDK's own policy model, NOT a replacement for Claude Code's
8
+ // plugin manifest. It gives the installer, validator, and security auditor
9
+ // a consistent contract to inspect before a Mod is enabled.
10
+
11
+ import { z } from 'zod';
12
+
13
+ export const ModCapabilitiesSchema = z.object({
14
+ // The Mod's unique id (kebab-case).
15
+ id: z.string().regex(/^[a-z][a-z0-9-]*$/),
16
+ version: z.string().regex(/^\d+\.\d+\.\d+$/, 'semver'),
17
+ // Event names this Mod registers handlers for.
18
+ hooks: z.array(z.string()),
19
+ // Mods API namespaces the Mod calls (e.g., ["ui.log", "fs.read"]).
20
+ apiAccess: z.array(z.string()),
21
+ // Filesystem paths or path patterns the Mod reads or writes.
22
+ filesystemAccess: z.array(z.string()),
23
+ // Whether the Mod makes network requests.
24
+ networkAccess: z.boolean().default(false),
25
+ // Whether the Mod spawns processes.
26
+ processExecution: z.boolean().default(false),
27
+ // Whether the Mod modifies submitted prompts or context.
28
+ modifiesPrompts: z.boolean().default(false),
29
+ // Whether the Mod modifies tool calls or arguments.
30
+ modifiesToolCalls: z.boolean().default(false),
31
+ // Whether the Mod changes model selection or effort.
32
+ modifiesModels: z.boolean().default(false),
33
+ // The autonomy level this Mod is allowed to operate at (for learning
34
+ // Mods; non-learning Mods default to L0 — collect evidence only).
35
+ learningAutonomyLevel: z.enum(['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6']).default('L0'),
36
+ });
37
+
38
+ export type ModCapabilities = z.infer<typeof ModCapabilitiesSchema>;
@@ -0,0 +1,43 @@
1
+ // packages/mod-sdk/src/claude-code-shim.ts
2
+ //
3
+ // Test-time implementation of the RUNTIME values a hooks module imports
4
+ // from the bare 'claude-code' specifier (the official state helpers
5
+ // atom / read / update — see plugins/<name>/hooks/register.ts). In a
6
+ // real session the Claude Code engine supplies them; in the kit's tests
7
+ // each plugin's vitest.config.ts aliases 'claude-code' to this module,
8
+ // whose helpers are thin wrappers over the MockRuntime's $.state (the
9
+ // same place the engine's own helpers bottom out).
10
+ //
11
+ // The signatures mirror the vendored official declarations in
12
+ // plugins/<name>/.claude-plugin/types/claude-code/index.d.ts: read()
13
+ // resolves to the stored value or the atom's initial; update() applies
14
+ // fn to the current value and stores the result.
15
+
16
+ import type { ModsApi } from './types/events.js';
17
+
18
+ /** A typed reference to one { plugin, key } state slot. */
19
+ export interface Atom<T> {
20
+ readonly ref: { readonly plugin: string; readonly key: string };
21
+ readonly initial: T;
22
+ }
23
+
24
+ /** Create an atom over one state slot; `initial` is the read fallback. */
25
+ export function atom<T>(ref: { plugin: string; key: string } & object, initial: T): Atom<T> {
26
+ return { ref, initial };
27
+ }
28
+
29
+ /** The $ surface the helpers need (a real `$` or the MockRuntime's). */
30
+ type StateApi = Pick<ModsApi, 'state'>;
31
+
32
+ /** Resolve the atom's stored value, or its initial when nothing is set. */
33
+ export async function read<T>($: StateApi, a: Atom<T>): Promise<T> {
34
+ const stored = await $.state.get<T>(a.ref);
35
+ return stored.value ?? a.initial;
36
+ }
37
+
38
+ /** Apply fn to the current value (initial when unset) and store it. */
39
+ export async function update<T>($: StateApi, a: Atom<T>, fn: (value: T) => T): Promise<T> {
40
+ const value = fn(await read<T>($, a));
41
+ await $.state.set(a.ref, value);
42
+ return value;
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ // packages/mod-sdk/src/index.ts
2
+ //
3
+ // Barrel for @agentic-sdlc-kit/mod-sdk.
4
+ //
5
+ // Architectural invariant: this package imports from
6
+ // @agentic-sdlc-kit/contracts and @agentic-sdlc-kit/core (for the policy
7
+ // evaluator and secret detector that Mods consume). It does NOT import
8
+ // `claude-code`. The host SDK types are declared by the SDK itself (see
9
+ // types/events.ts).
10
+
11
+ export * from './types/index.js';
12
+ export * from './capabilities/index.js';
13
+ export * from './middleware/index.js';
14
+ export * from './testing/index.js';
@@ -0,0 +1,70 @@
1
+ // packages/mod-sdk/src/middleware/compose.test.ts
2
+ import { describe, expect, it } from 'vitest';
3
+ import { compose } from './compose.js';
4
+ import type { Handler, ToolCallEvent, ModsApi } from '../types/events.js';
5
+
6
+ // A fake ModsApi that doesn't depend on MockRuntime, for direct compose tests.
7
+ const fakeApi: ModsApi = {
8
+ ui: { log: () => {}, open: () => {}, resolve: () => {} },
9
+ fs: { read: async () => '', write: async () => {} },
10
+ state: { get: () => undefined, set: () => {} },
11
+ http: {
12
+ fetch: async () => {
13
+ throw new Error('no');
14
+ },
15
+ },
16
+ };
17
+
18
+ describe('compose', () => {
19
+ it('runs handlers in registration order and forwards through next', async () => {
20
+ const calls: string[] = [];
21
+ const h1: Handler<'tool.call'> = async ($, e, next) => {
22
+ calls.push('h1-before');
23
+ const r = await next(e);
24
+ calls.push('h1-after');
25
+ return r;
26
+ };
27
+ const h2: Handler<'tool.call'> = async ($, e, next) => {
28
+ calls.push('h2-before');
29
+ const r = await next(e);
30
+ calls.push('h2-after');
31
+ return r;
32
+ };
33
+ const terminal: Handler<'tool.call'> = async ($, e, next) => {
34
+ calls.push('terminal');
35
+ return next(e);
36
+ };
37
+ const composed = compose([h1, h2, terminal]);
38
+ const result = await composed(
39
+ fakeApi,
40
+ { tool: 'Bash', input: {} } as ToolCallEvent,
41
+ () => 'done',
42
+ );
43
+ expect(result).toBe('done');
44
+ expect(calls).toEqual(['h1-before', 'h2-before', 'terminal', 'h2-after', 'h1-after']);
45
+ });
46
+
47
+ it('short-circuits when a handler answers without calling next', async () => {
48
+ const calls: string[] = [];
49
+ const h1: Handler<'tool.call'> = async ($, e, next) => {
50
+ calls.push('h1');
51
+ return next(e);
52
+ };
53
+ const h2: Handler<'tool.call'> = async () => {
54
+ calls.push('h2-answer');
55
+ return { deny: 'blocked by h2' };
56
+ };
57
+ const h3: Handler<'tool.call'> = async ($, e, next) => {
58
+ calls.push('h3-should-not-run');
59
+ return next(e);
60
+ };
61
+ const composed = compose([h1, h2, h3]);
62
+ const result = await composed(
63
+ fakeApi,
64
+ { tool: 'Bash', input: {} } as ToolCallEvent,
65
+ () => 'should-not-reach',
66
+ );
67
+ expect(result).toEqual({ deny: 'blocked by h2' });
68
+ expect(calls).toEqual(['h1', 'h2-answer']);
69
+ });
70
+ });
@@ -0,0 +1,29 @@
1
+ // packages/mod-sdk/src/middleware/compose.ts
2
+ //
3
+ // Compose multiple handlers for the same event into a single handler.
4
+ // Handlers run in registration order. Each handler decides whether to
5
+ // call next(e) (observe/rewrite and forward) or return a result without
6
+ // calling next (answer).
7
+ //
8
+ // This lets a Mod register multiple policies for `tool.call` (e.g., a
9
+ // shell policy, a git policy, a migration policy) without each policy
10
+ // needing to know about the others.
11
+
12
+ import type { Handler, EventName, EventOf, ModsApi } from '../types/events.js';
13
+
14
+ export function compose<N extends EventName>(handlers: ReadonlyArray<Handler<N>>): Handler<N> {
15
+ return async ($: ModsApi, e: EventOf<N>, next: (e: EventOf<N>) => Promise<unknown> | unknown) => {
16
+ // Build the chain from the inside out: the last handler's next is the
17
+ // caller's next; the previous handler's next is a function that calls
18
+ // the last handler with the caller's next as its next; etc.
19
+ let chain: (e: EventOf<N>) => Promise<unknown> | unknown = next;
20
+ for (let i = handlers.length - 1; i >= 0; i--) {
21
+ const h = handlers[i];
22
+ if (!h) continue;
23
+ const currentNext = chain;
24
+ const currentHandler = h;
25
+ chain = (ev: EventOf<N>) => currentHandler($, ev, currentNext);
26
+ }
27
+ return chain(e);
28
+ };
29
+ }
@@ -0,0 +1,2 @@
1
+ // packages/mod-sdk/src/middleware/index.ts
2
+ export * from './compose.js';
@@ -0,0 +1,2 @@
1
+ // packages/mod-sdk/src/testing/index.ts
2
+ export * from './mock-runtime.js';
@@ -0,0 +1,264 @@
1
+ // packages/mod-sdk/src/testing/mock-runtime.test.ts
2
+ import { describe, expect, it } from 'vitest';
3
+ import { MockRuntime } from './mock-runtime.js';
4
+ import type { RegisterFn, ToolCallEvent } from '../types/events.js';
5
+
6
+ describe('MockRuntime', () => {
7
+ it('captures registrations from a register function', () => {
8
+ const runtime = new MockRuntime();
9
+ const register: RegisterFn = (on) => {
10
+ on('tool.call', async (_, e, next) => next(e));
11
+ on('tool.check', async (_, e, next) => next(e));
12
+ };
13
+ runtime.load(register);
14
+ expect(runtime.registrationCount()).toBe(2);
15
+ expect(runtime.registrationCount('tool.call')).toBe(1);
16
+ });
17
+
18
+ it('drains streaming handlers (async function*) and uses their return value', async () => {
19
+ const runtime = new MockRuntime();
20
+ runtime.setHostResult({ usage: { input_tokens: 5 } });
21
+ runtime.setHostChunks(['chunk-1', 'chunk-2']);
22
+ // Streaming events (turn.step) take the generator form; the official
23
+ // delegation is `const result = yield* next(e)`.
24
+ const register: RegisterFn = (on) => {
25
+ on('turn.step', async function* ($, _e, next) {
26
+ $.ui.log('stream: before');
27
+ const result = yield* next(_e);
28
+ $.ui.log('stream: after');
29
+ return result;
30
+ });
31
+ };
32
+ runtime.load(register);
33
+ const result = await runtime.fire('turn.step', { model: 'sonnet' });
34
+ expect(result.forwarded).toBe(true);
35
+ expect(result.value).toEqual({ usage: { input_tokens: 5 } });
36
+ expect(result.chunks).toEqual(['chunk-1', 'chunk-2']);
37
+ expect(runtime.getLogs()).toContain('stream: before');
38
+ expect(runtime.getLogs()).toContain('stream: after');
39
+ });
40
+
41
+ it('captures a rewrite via next({ ...e, model }) on a streaming event', async () => {
42
+ const runtime = new MockRuntime();
43
+ const register: RegisterFn = (on) => {
44
+ on('turn.step', async function* (_$, e, next) {
45
+ return yield* next({ ...e, model: 'opus' });
46
+ });
47
+ };
48
+ runtime.load(register);
49
+ const result = await runtime.fire('turn.step', { model: 'sonnet' });
50
+ expect(result.forwarded).toBe(true);
51
+ expect(result.terminalEvent).toMatchObject({ model: 'opus' });
52
+ });
53
+
54
+ it('fires an event and forwards when no handler answers', async () => {
55
+ const runtime = new MockRuntime();
56
+ const register: RegisterFn = (on) => {
57
+ on('tool.call', async (_, e, next) => next(e));
58
+ };
59
+ runtime.load(register);
60
+ const result = await runtime.fire('tool.call', { tool: 'Bash' });
61
+ expect(result.answered).toBe(false);
62
+ expect(result.forwarded).toBe(true);
63
+ });
64
+
65
+ it('fires an event and captures a deny answer', async () => {
66
+ const runtime = new MockRuntime();
67
+ const register: RegisterFn = (on) => {
68
+ on('tool.call', async (_, e: ToolCallEvent, next) => {
69
+ if (e.tool === 'Bash') return { deny: 'no' };
70
+ return next(e);
71
+ });
72
+ };
73
+ runtime.load(register);
74
+ const result = await runtime.fire('tool.call', { tool: 'Bash' });
75
+ expect(result.answered).toBe(true);
76
+ expect(result.value).toEqual({ deny: 'no' });
77
+ });
78
+
79
+ it('marks a forwarded host result as not answered, a rewritten result as answered', async () => {
80
+ const runtime = new MockRuntime();
81
+ runtime.setHostResult({ text: 'the host text' });
82
+ const register: RegisterFn = (on) => {
83
+ on('tool.call', async (_, _e, next) => next(_e));
84
+ on('tool.check', async (_, _e, next) => {
85
+ const r = (await next(_e)) as { text: string };
86
+ return { ...r, text: r.text.toUpperCase() };
87
+ });
88
+ };
89
+ runtime.load(register);
90
+ const forwarded = await runtime.fire('tool.call', { tool: 'Bash' });
91
+ expect(forwarded.forwarded).toBe(true);
92
+ expect(forwarded.answered).toBe(false);
93
+ expect(forwarded.value).toEqual({ text: 'the host text' });
94
+ const rewritten = await runtime.fire('tool.check', { tool: 'Bash', input: {} });
95
+ expect(rewritten.answered).toBe(true);
96
+ expect(rewritten.value).toEqual({ text: 'THE HOST TEXT' });
97
+ });
98
+
99
+ it("respects the { tool: 'Bash' } matcher", async () => {
100
+ const runtime = new MockRuntime();
101
+ const register: RegisterFn = (on) => {
102
+ on('tool.call', { tool: 'Bash' }, async () => {
103
+ return { deny: 'bash blocked' };
104
+ });
105
+ };
106
+ runtime.load(register);
107
+ const bashResult = await runtime.fire('tool.call', { tool: 'Bash' });
108
+ const editResult = await runtime.fire('tool.call', { tool: 'Edit' });
109
+ expect(bashResult.answered).toBe(true);
110
+ expect(editResult.answered).toBe(false);
111
+ });
112
+
113
+ it('respects array and RegExp matchers', async () => {
114
+ const runtime = new MockRuntime();
115
+ const register: RegisterFn = (on) => {
116
+ on('tool.call', { tool: ['Edit', 'Write'] }, async () => ({ deny: 'file writes blocked' }));
117
+ on('tool.call', { tool: /^mcp__github__/ }, async () => ({ deny: 'mcp blocked' }));
118
+ };
119
+ runtime.load(register);
120
+ expect((await runtime.fire('tool.call', { tool: 'Write' })).answered).toBe(true);
121
+ expect((await runtime.fire('tool.call', { tool: 'Edit' })).answered).toBe(true);
122
+ expect((await runtime.fire('tool.call', { tool: 'Read' })).answered).toBe(false);
123
+ expect((await runtime.fire('tool.call', { tool: 'mcp__github__create_issue' })).answered).toBe(
124
+ true,
125
+ );
126
+ });
127
+
128
+ it('captures $.ui.log calls', async () => {
129
+ const runtime = new MockRuntime();
130
+ const register: RegisterFn = (on) => {
131
+ on('tool.call', async ($, e, next) => {
132
+ $.ui.log('hello from handler');
133
+ return next(e);
134
+ });
135
+ };
136
+ runtime.load(register);
137
+ await runtime.fire('tool.call', { tool: 'Bash' });
138
+ expect(runtime.getLogs()).toContain('hello from handler');
139
+ });
140
+
141
+ it('supports $.state.get and $.state.set (async, StateRead-wrapped)', async () => {
142
+ const runtime = new MockRuntime();
143
+ const register: RegisterFn = (on) => {
144
+ on('tool.call', async ($, e, next) => {
145
+ await $.state.set({ plugin: 'test-mod', key: 'greeting' }, 'value');
146
+ const read = await $.state.get<string>({ plugin: 'test-mod', key: 'greeting' });
147
+ $.ui.log(`got ${read.value ?? '<missing>'}`);
148
+ return next(e);
149
+ });
150
+ };
151
+ runtime.load(register);
152
+ await runtime.fire('tool.call', { tool: 'Bash' });
153
+ expect(runtime.getLogs()).toContain('got value');
154
+ expect(runtime.getState<string>({ plugin: 'test-mod', key: 'greeting' })).toBe('value');
155
+ });
156
+
157
+ it('runs the chained .catch handler when the hook throws (fail-closed)', async () => {
158
+ const runtime = new MockRuntime();
159
+ const register: RegisterFn = (on) => {
160
+ on('tool.call', { tool: 'Bash' }, async () => {
161
+ throw new Error('hook exploded');
162
+ }).catch(() => ({ deny: 'fail closed' }));
163
+ };
164
+ runtime.load(register);
165
+ const result = await runtime.fire('tool.call', { tool: 'Bash' });
166
+ expect(result.answered).toBe(true);
167
+ expect(result.value).toEqual({ deny: 'fail closed' });
168
+ });
169
+
170
+ it('skips a throwing hook that has no .catch (host behavior)', async () => {
171
+ const runtime = new MockRuntime();
172
+ const register: RegisterFn = (on) => {
173
+ on('tool.call', { tool: 'Bash' }, async () => {
174
+ throw new Error('hook exploded');
175
+ });
176
+ };
177
+ runtime.load(register);
178
+ const result = await runtime.fire('tool.call', { tool: 'Bash' });
179
+ expect(result.forwarded).toBe(true);
180
+ expect(result.answered).toBe(false);
181
+ });
182
+
183
+ it('mocks $.ui.ask: resolves queued answers, rejects when nobody can answer', async () => {
184
+ const runtime = new MockRuntime();
185
+ runtime.queueAskAnswers('Run it');
186
+ const register: RegisterFn = (on) => {
187
+ on('tool.call', { tool: 'Bash' }, async ($, _e, next) => {
188
+ let answer = 'Refuse';
189
+ try {
190
+ answer = await $.ui.ask('run?', ['Run it', 'Refuse']);
191
+ } catch {
192
+ // nobody to ask
193
+ }
194
+ return answer === 'Run it' ? next(_e) : { deny: 'refused' };
195
+ });
196
+ };
197
+ runtime.load(register);
198
+ const approved = await runtime.fire('tool.call', { tool: 'Bash' });
199
+ expect(approved.forwarded).toBe(true);
200
+ const refused = await runtime.fire('tool.call', { tool: 'Bash' });
201
+ expect(refused.answered).toBe(true);
202
+ expect((refused.value as { deny: string }).deny).toBe('refused');
203
+ });
204
+
205
+ it('mocks $.process.run with queued results and records calls', async () => {
206
+ const runtime = new MockRuntime();
207
+ runtime.queueProcessResults({ stdout: 'diff --cached contents', exitCode: 0 });
208
+ const register: RegisterFn = (on) => {
209
+ on('tool.call', { tool: 'Bash' }, async ($, _e, next) => {
210
+ const r = await $.process.run(['git', 'diff', '--cached']);
211
+ return r.exitCode === 0 ? next(_e) : { deny: 'git failed' };
212
+ });
213
+ };
214
+ runtime.load(register);
215
+ const ok = await runtime.fire('tool.call', { tool: 'Bash' });
216
+ expect(ok.forwarded).toBe(true);
217
+ expect(runtime.getProcessCalls()).toEqual([['git', 'diff', '--cached']]);
218
+ // No result queued anymore: $.process.run throws inside the hook. With
219
+ // no chained .catch the host SKIPS the hook — the call goes through.
220
+ const skipped = await runtime.fire('tool.call', { tool: 'Bash' });
221
+ expect(skipped.forwarded).toBe(true);
222
+ expect(skipped.answered).toBe(false);
223
+ });
224
+
225
+ it('mocks the async $.clock.now / $.session.id / $.session.cwd', async () => {
226
+ const runtime = new MockRuntime(1_000_000);
227
+ runtime.setSession('S-42', '/repo');
228
+ const register: RegisterFn = (on) => {
229
+ on('session.start', async ($, _e, next) => {
230
+ const t = await $.clock.now();
231
+ const s = await $.session.id();
232
+ const cwd = await $.session.cwd();
233
+ $.ui.log(`t=${t} s=${s} cwd=${cwd}`);
234
+ return next(_e);
235
+ });
236
+ };
237
+ runtime.load(register);
238
+ await runtime.fire('session.start', {});
239
+ expect(runtime.getLogs()).toContain('t=1000000 s=S-42 cwd=/repo');
240
+ runtime.advanceClock(2_500);
241
+ await runtime.fire('session.start', {});
242
+ expect(runtime.getLogs()).toContain('t=1002500 s=S-42 cwd=/repo');
243
+ });
244
+
245
+ it('mocks $.fs.exists / $.fs.list / $.command.register / $.ui.status', async () => {
246
+ const runtime = new MockRuntime();
247
+ runtime.setListing('.ai/reports/runs', ['run-1.jsonl']);
248
+ const register: RegisterFn = (on) => {
249
+ on('session.start', async ($, e, next) => {
250
+ await $.command.register({ name: 'kit-status', description: 'status' });
251
+ const listed = await $.fs.list('.ai/reports/runs');
252
+ const exists = await $.fs.exists('.ai/reports/runs');
253
+ $.ui.status(`files=${listed.length} exists=${exists}`);
254
+ return next(e);
255
+ });
256
+ };
257
+ runtime.load(register);
258
+ await runtime.fire('session.start', {});
259
+ expect(runtime.getRegisteredCommands()).toEqual([
260
+ { name: 'kit-status', description: 'status' },
261
+ ]);
262
+ expect(runtime.getStatuses()).toContain('files=1 exists=true');
263
+ });
264
+ });