@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,452 @@
1
+ // packages/mod-sdk/src/testing/mock-runtime.ts
2
+ //
3
+ // MockRuntime: captures registered handlers and lets tests fire events
4
+ // without launching Claude Code. This is the testing utility RESEARCH.md §6
5
+ // recommends ("packages/testing should make event middleware testable
6
+ // without starting a Claude Code session").
7
+ //
8
+ // The mock mirrors the REAL host contract (verified against
9
+ // @anthropic-ai/claude-code 2.1.329 — see types/events.ts header), so a
10
+ // test that passes here exercises the shapes Claude Code actually
11
+ // delivers:
12
+ // - tool.call events carry the tool's arguments as fields (e.command),
13
+ // tool.check carries them under e.input;
14
+ // - on(...) returns a registration with .catch(handler); when a hook
15
+ // throws, the .catch handler's return value replaces its contribution
16
+ // (and without one the hook is skipped, like the host does);
17
+ // - turn.step's next is an async generator, so `yield* next(e)` works;
18
+ // - $.ui.ask / $.process.run / $.clock.now / $.session.id are mocked
19
+ // explicitly (tests queue answers and process results) — nothing is
20
+ // fabricated behind the test's back;
21
+ // - $.clock.now / $.session.id / $.session.cwd / $.state.get / $.state.set
22
+ // are ASYNC and state reads resolve to StateRead<T> (unwrap `.value`),
23
+ // exactly as on the official engine.
24
+
25
+ import type {
26
+ EventName,
27
+ EventOf,
28
+ Matcher,
29
+ ModsApi,
30
+ On,
31
+ RegisterFn,
32
+ StateRead,
33
+ StateRef,
34
+ } from '../types/events.js';
35
+
36
+ interface Registration {
37
+ event: EventName;
38
+ matcher?: Matcher;
39
+ // Stored as a loose function; the type narrowing happens at fire() time.
40
+ handler: (...args: never[]) => unknown;
41
+ // The .catch(handler) error handler, if one was chained.
42
+ catchHandler?: (error: unknown) => unknown;
43
+ }
44
+
45
+ export interface FireResult {
46
+ // The value the host would receive from the handler chain (the answer,
47
+ // or what the terminal behavior resolved to).
48
+ value: unknown;
49
+ // True if any handler returned a result without calling next (answer).
50
+ answered: boolean;
51
+ // True if the chain forwarded to the host's own behavior (next called).
52
+ forwarded: boolean;
53
+ // The event the host's own behavior received (set when forwarded) —
54
+ // lets tests assert rewrites (e.g. next({ ...e, model })).
55
+ terminalEvent?: unknown;
56
+ // For streaming events (turn.step): the chunks that were forwarded.
57
+ chunks: unknown[];
58
+ }
59
+
60
+ function isAsyncGenerator(v: unknown): v is AsyncGenerator<unknown, unknown, unknown> {
61
+ return (
62
+ v !== null &&
63
+ typeof v === 'object' &&
64
+ typeof (v as AsyncGenerator).next === 'function' &&
65
+ typeof (v as AsyncGenerator)[Symbol.asyncIterator] === 'function'
66
+ );
67
+ }
68
+
69
+ function matcherFieldMatches(field: unknown, value: unknown): boolean {
70
+ if (field instanceof RegExp) {
71
+ return typeof value === 'string' && field.test(value);
72
+ }
73
+ if (Array.isArray(field)) {
74
+ return field.some((f) => matcherFieldMatches(f, value));
75
+ }
76
+ return field === value;
77
+ }
78
+
79
+ export class MockRuntime {
80
+ private registrations: Array<Registration> = [];
81
+ private logs: string[] = [];
82
+ private statuses: string[] = [];
83
+ private stateStore: Record<string, unknown> = {};
84
+ private poisonedStateKeys = new Set<string>();
85
+ private fsStore: Record<string, string> = {};
86
+ private fsListings: Record<string, string[]> = {};
87
+ // $.ui.ask: queued answers popped FIFO; when empty, ask REJECTS (nobody
88
+ // to ask — the same refusal a headless claude -p run produces).
89
+ private askAnswers: string[] = [];
90
+ // $.process.run: queued results popped FIFO; when empty, run throws
91
+ // (tests must be explicit about what git/... would return).
92
+ private processResults: Array<{ stdout: string; stderr: string; exitCode: number }> = [];
93
+ private processCalls: Array<ReadonlyArray<string>> = [];
94
+ private registeredCommands: Array<{ name: string; description: string }> = [];
95
+ private clockNowMs: number;
96
+ private sessionIdentifier = 'session-mock';
97
+ private sessionCwd = '/project';
98
+ // What the host's own behavior (the terminal next) resolves to.
99
+ private hostResult: unknown;
100
+ // Chunks the host would stream for turn.step.
101
+ private hostChunks: unknown[] = [];
102
+
103
+ constructor(nowMs: number = Date.parse('2026-11-20T12:00:00.000Z')) {
104
+ this.clockNowMs = nowMs;
105
+ }
106
+
107
+ readonly api: ModsApi = {
108
+ ui: {
109
+ log: (msg: string) => {
110
+ this.logs.push(msg);
111
+ },
112
+ status: (text: string) => {
113
+ this.statuses.push(text);
114
+ },
115
+ ask: async (_question: string, _options: ReadonlyArray<string>) => {
116
+ const answer = this.askAnswers.shift();
117
+ if (answer === undefined) {
118
+ throw new Error('mock ask: nobody to ask (headless run)');
119
+ }
120
+ return answer;
121
+ },
122
+ },
123
+ fs: {
124
+ read: async (path: string) => {
125
+ if (!(path in this.fsStore)) throw new Error(`mock fs: ${path} not found`);
126
+ return this.fsStore[path]!;
127
+ },
128
+ write: async (path: string, content: string) => {
129
+ this.fsStore[path] = content;
130
+ },
131
+ exists: async (path: string) => path in this.fsStore || path in this.fsListings,
132
+ list: async (path: string) => {
133
+ const listed = this.fsListings[path];
134
+ if (!listed) throw new Error(`mock fs: ${path} not listable`);
135
+ return [...listed];
136
+ },
137
+ },
138
+ process: {
139
+ run: async (args: ReadonlyArray<string>) => {
140
+ this.processCalls.push(args);
141
+ const result = this.processResults.shift();
142
+ if (result === undefined) {
143
+ throw new Error(`mock process: no result queued for [${args.join(' ')}]`);
144
+ }
145
+ return result;
146
+ },
147
+ },
148
+ command: {
149
+ register: async (cmd: { name: string; description: string }) => {
150
+ this.registeredCommands.push({ name: cmd.name, description: cmd.description });
151
+ },
152
+ },
153
+ session: {
154
+ id: async () => this.sessionIdentifier,
155
+ cwd: async () => this.sessionCwd,
156
+ },
157
+ clock: {
158
+ now: async () => this.clockNowMs,
159
+ },
160
+ state: {
161
+ get: async <T>(ref: StateRef): Promise<StateRead<T>> => {
162
+ const key = MockRuntime.refKey(ref);
163
+ if (this.poisonedStateKeys.has(key)) {
164
+ throw new Error(`mock state: ${key} is poisoned`);
165
+ }
166
+ return { value: this.stateStore[key] as T | undefined };
167
+ },
168
+ set: async <T>(ref: StateRef, value: T): Promise<void> => {
169
+ this.stateStore[MockRuntime.refKey(ref)] = value;
170
+ },
171
+ },
172
+ http: {
173
+ fetch: async () => {
174
+ throw new Error('mock http: networkAccess not allowed in tests by default');
175
+ },
176
+ },
177
+ };
178
+
179
+ /**
180
+ * The `on` function passed to a Mod's register(). Captures registrations
181
+ * and returns a registration object with a .catch(handler) method, the
182
+ * same shape the real host returns.
183
+ */
184
+ readonly on: On = ((event: string, ...rest: unknown[]) => {
185
+ let matcher: Matcher | undefined;
186
+ let handler: (...args: never[]) => unknown;
187
+ if (rest.length === 1) {
188
+ const h = rest[0] as (...args: never[]) => unknown;
189
+ handler = h;
190
+ } else {
191
+ matcher = rest[0] as Matcher;
192
+ handler = rest[1] as (...args: never[]) => unknown;
193
+ }
194
+ const registration: Registration = { event: event as EventName, matcher, handler };
195
+ this.registrations.push(registration);
196
+ return {
197
+ catch: (catchHandler: (error: unknown) => unknown) => {
198
+ registration.catchHandler = catchHandler;
199
+ },
200
+ };
201
+ }) as unknown as On;
202
+
203
+ /**
204
+ * Load a Mod by calling its register function with this runtime's `on`.
205
+ */
206
+ load(register: RegisterFn): void {
207
+ register(this.on);
208
+ }
209
+
210
+ /**
211
+ * Fire an event. Builds the middleware chain from every registration
212
+ * whose matcher accepts the event (registration order = outside-in, the
213
+ * same order the host stacks hooks) and returns what the host would see.
214
+ */
215
+ async fire<N extends EventName>(event: N, e: EventOf<N>): Promise<FireResult> {
216
+ const matching = this.registrations.filter(
217
+ (r) => r.event === event && this.matcherMatches(r.matcher, e),
218
+ );
219
+ const result: FireResult = { value: undefined, answered: false, forwarded: false, chunks: [] };
220
+ if (matching.length === 0) {
221
+ // No hook matches: the event goes straight to the host's own
222
+ // behavior, unimpeded.
223
+ return { value: this.hostResult, answered: false, forwarded: true, chunks: [] };
224
+ }
225
+
226
+ // The host's own behavior: for streaming events it is an async
227
+ // generator (so `yield* next(e)` delegates); otherwise it resolves to
228
+ // the configured host result.
229
+ const terminal = async (ev: EventOf<N>): Promise<unknown> => {
230
+ result.forwarded = true;
231
+ result.terminalEvent = ev;
232
+ return this.hostResult;
233
+ };
234
+ const terminalStream = async function* (
235
+ this: MockRuntime,
236
+ ev: EventOf<N>,
237
+ ): AsyncGenerator<unknown, unknown, unknown> {
238
+ result.forwarded = true;
239
+ result.terminalEvent = ev;
240
+ for (const chunk of this.hostChunks) {
241
+ result.chunks.push(chunk);
242
+ yield chunk;
243
+ }
244
+ return this.hostResult;
245
+ };
246
+
247
+ const isStreaming = event === 'turn.step';
248
+ type LinkResult = Promise<unknown> | unknown | AsyncGenerator<unknown, unknown, unknown>;
249
+ let chain: (ev: EventOf<N>) => LinkResult = isStreaming
250
+ ? (ev: EventOf<N>) => terminalStream.call(this, ev)
251
+ : (ev: EventOf<N>) => terminal(ev);
252
+
253
+ // Drain a generator to its return value (used on error/skip paths and
254
+ // once at the outermost level).
255
+ const drain = async (gen: AsyncGenerator<unknown, unknown, unknown>): Promise<unknown> => {
256
+ const it = gen[Symbol.asyncIterator]();
257
+ let r = await it.next();
258
+ while (!r.done) {
259
+ r = await it.next();
260
+ }
261
+ return r.value;
262
+ };
263
+
264
+ for (let i = matching.length - 1; i >= 0; i--) {
265
+ const reg = matching[i];
266
+ if (!reg) continue;
267
+ const currentNext = chain;
268
+ const currentHandler = reg.handler;
269
+ const currentCatch = reg.catchHandler;
270
+ // Error path: a chained .catch handler replaces the hook's
271
+ // contribution; without one the host SKIPS the hook (the rest of
272
+ // the chain runs as if it weren't there).
273
+ const handleError = async (err: unknown, ev: EventOf<N>): Promise<unknown> => {
274
+ if (currentCatch !== undefined) {
275
+ return currentCatch(err);
276
+ }
277
+ const downstream = currentNext(ev);
278
+ if (isAsyncGenerator(downstream)) {
279
+ return drain(downstream);
280
+ }
281
+ return downstream;
282
+ };
283
+ // The link must pass a downstream GENERATOR through synchronously so
284
+ // an outer streaming handler can delegate with `yield* next(e)`.
285
+ chain = (ev: EventOf<N>): LinkResult => {
286
+ let out: unknown;
287
+ try {
288
+ // The handler signature is ($, e, next).
289
+ out = currentHandler(this.api as never, ev as never, currentNext as never);
290
+ } catch (err) {
291
+ return handleError(err, ev);
292
+ }
293
+ if (
294
+ out !== null &&
295
+ typeof out === 'object' &&
296
+ typeof (out as PromiseLike<unknown>).then === 'function' &&
297
+ !isAsyncGenerator(out)
298
+ ) {
299
+ // A plain async handler: route rejections through the error path.
300
+ return (out as Promise<unknown>).then(undefined, (err) => handleError(err, ev));
301
+ }
302
+ return out;
303
+ };
304
+ }
305
+
306
+ // Run the outermost link. A streaming handler surfaces a generator —
307
+ // drain it (its yields already forwarded through the chain).
308
+ let value: unknown;
309
+ const outer = chain(e);
310
+ if (isAsyncGenerator(outer)) {
311
+ value = await drain(outer);
312
+ } else {
313
+ value = await outer;
314
+ }
315
+ result.value = value;
316
+ // `answered` = the chain produced a value the host alone would not
317
+ // have: a hook short-circuited (or rewrote the result) instead of
318
+ // merely forwarding the host's own behavior.
319
+ result.answered = value !== undefined && !(result.forwarded && value === this.hostResult);
320
+ return result;
321
+ }
322
+
323
+ /**
324
+ * Get the captured UI logs (from $.ui.log calls).
325
+ */
326
+ getLogs(): string[] {
327
+ return [...this.logs];
328
+ }
329
+
330
+ /**
331
+ * Get the captured status lines (from $.ui.status calls).
332
+ */
333
+ getStatuses(): string[] {
334
+ return [...this.statuses];
335
+ }
336
+
337
+ /**
338
+ * Get the number of registrations for a given event.
339
+ */
340
+ registrationCount(event?: EventName): number {
341
+ if (event === undefined) return this.registrations.length;
342
+ return this.registrations.filter((r) => r.event === event).length;
343
+ }
344
+
345
+ /** Set mock filesystem content for $.fs.read. */
346
+ setFile(path: string, content: string): void {
347
+ this.fsStore[path] = content;
348
+ }
349
+
350
+ /** Set a mock directory listing for $.fs.list. */
351
+ setListing(path: string, entries: string[]): void {
352
+ this.fsListings[path] = entries;
353
+ }
354
+
355
+ /** Get the recorded state (for assertions). */
356
+ getState<T>(ref: StateRef): T | undefined {
357
+ return this.stateStore[MockRuntime.refKey(ref)] as T | undefined;
358
+ }
359
+
360
+ /** Set state a test wants a hook to read via $.state.get. */
361
+ setState<T>(ref: StateRef, value: T): void {
362
+ this.stateStore[MockRuntime.refKey(ref)] = value;
363
+ }
364
+
365
+ /** Make $.state.get throw for a key (to exercise fail-closed .catch). */
366
+ poisonState(plugin: string, key: string): void {
367
+ this.poisonedStateKeys.add(`${plugin}.${key}`);
368
+ }
369
+
370
+ /** Queue the labels $.ui.ask resolves to, in order (FIFO). */
371
+ queueAskAnswers(...answers: string[]): void {
372
+ this.askAnswers.push(...answers);
373
+ }
374
+
375
+ /** Queue $.process.run results, in order (FIFO). */
376
+ queueProcessResults(
377
+ ...results: Array<{ stdout: string; stderr?: string; exitCode?: number }>
378
+ ): void {
379
+ this.processResults.push(
380
+ ...results.map((r) => ({
381
+ stdout: r.stdout,
382
+ stderr: r.stderr ?? '',
383
+ exitCode: r.exitCode ?? 0,
384
+ })),
385
+ );
386
+ }
387
+
388
+ /** The argument arrays $.process.run was called with, in order. */
389
+ getProcessCalls(): Array<ReadonlyArray<string>> {
390
+ return [...this.processCalls];
391
+ }
392
+
393
+ /** Commands registered via $.command.register. */
394
+ getRegisteredCommands(): Array<{ name: string; description: string }> {
395
+ return [...this.registeredCommands];
396
+ }
397
+
398
+ /** Set what the host's own behavior resolves to (the terminal next). */
399
+ setHostResult(value: unknown): void {
400
+ this.hostResult = value;
401
+ }
402
+
403
+ /** Set the chunks the host streams for turn.step. */
404
+ setHostChunks(chunks: unknown[]): void {
405
+ this.hostChunks = [...chunks];
406
+ }
407
+
408
+ /** Set the mock clock (ms since epoch) — `await $.clock.now()` returns it. */
409
+ setNow(nowMs: number): void {
410
+ this.clockNowMs = nowMs;
411
+ }
412
+
413
+ /** Advance the mock clock. */
414
+ advanceClock(ms: number): void {
415
+ this.clockNowMs += ms;
416
+ }
417
+
418
+ /** The current mock clock value. */
419
+ now(): number {
420
+ return this.clockNowMs;
421
+ }
422
+
423
+ /** Set the session identity `await $.session.id()` returns. */
424
+ setSession(sessionId: string, cwd: string = '/project'): void {
425
+ this.sessionIdentifier = sessionId;
426
+ this.sessionCwd = cwd;
427
+ }
428
+
429
+ private static refKey(ref: StateRef): string {
430
+ return `${ref.plugin}.${ref.key}`;
431
+ }
432
+
433
+ private matcherMatches<N extends EventName>(
434
+ matcher: Matcher | undefined,
435
+ e: EventOf<N>,
436
+ ): boolean {
437
+ if (!matcher) return true;
438
+ if (matcher.tool !== undefined) {
439
+ const tool = (e as unknown as { tool?: unknown }).tool;
440
+ if (!matcherFieldMatches(matcher.tool, tool)) return false;
441
+ }
442
+ if (matcher.command !== undefined) {
443
+ const command = (e as unknown as { command?: unknown }).command;
444
+ if (!matcherFieldMatches(matcher.command, command)) return false;
445
+ }
446
+ if (matcher.isReadOnly !== undefined) {
447
+ const isReadOnly = (e as unknown as { isReadOnly?: unknown }).isReadOnly;
448
+ if (!matcherFieldMatches(matcher.isReadOnly, isReadOnly)) return false;
449
+ }
450
+ return true;
451
+ }
452
+ }