@leitwerk-dev/test-support 0.2.0 → 0.3.0

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 (130) hide show
  1. package/dist/{chunk-KPSK7EMY.js → chunk-5BZSJ4OO.js} +22 -157
  2. package/dist/chunk-5BZSJ4OO.js.map +1 -0
  3. package/dist/{chunk-2IICIB6D.js → chunk-E4Y7XND5.js} +40 -4
  4. package/dist/chunk-E4Y7XND5.js.map +1 -0
  5. package/dist/{chunk-JUH3LUYK.js → chunk-EXHTWQAE.js} +5 -1
  6. package/dist/chunk-EXHTWQAE.js.map +1 -0
  7. package/dist/chunk-KJVNI2UP.js +17 -0
  8. package/dist/chunk-KJVNI2UP.js.map +1 -0
  9. package/dist/{chunk-7I4OCTF3.js → chunk-OE4NHDVS.js} +15 -4
  10. package/dist/chunk-OE4NHDVS.js.map +1 -0
  11. package/dist/chunk-P2FF4AP7.js +72 -0
  12. package/dist/chunk-P2FF4AP7.js.map +1 -0
  13. package/dist/chunk-RY6Y6V5E.js +54 -0
  14. package/dist/chunk-RY6Y6V5E.js.map +1 -0
  15. package/dist/compact-process-detail-fixture.d.ts +3 -0
  16. package/dist/compact-process-detail-fixture.d.ts.map +1 -1
  17. package/dist/extension-integration-harness.d.ts +357 -0
  18. package/dist/extension-integration-harness.d.ts.map +1 -0
  19. package/dist/fakes/fake-git-ops.d.ts +12 -0
  20. package/dist/fakes/fake-git-ops.d.ts.map +1 -1
  21. package/dist/fakes/fake-llm.d.ts +11 -0
  22. package/dist/fakes/fake-llm.d.ts.map +1 -1
  23. package/dist/fakes/index.d.ts +1 -1
  24. package/dist/fakes/index.d.ts.map +1 -1
  25. package/dist/fakes/index.js +105 -4
  26. package/dist/fakes/index.js.map +1 -1
  27. package/dist/fixtures.d.ts +2 -0
  28. package/dist/fixtures.d.ts.map +1 -1
  29. package/dist/fixtures.js +157 -2
  30. package/dist/fixtures.js.map +1 -1
  31. package/dist/http-launch.d.ts +2 -1
  32. package/dist/http-launch.d.ts.map +1 -1
  33. package/dist/index.d.ts +6 -13
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +13 -119
  36. package/dist/index.js.map +1 -1
  37. package/dist/integration-harness.d.ts +36 -1
  38. package/dist/integration-harness.d.ts.map +1 -1
  39. package/dist/integration.d.ts +3 -3
  40. package/dist/integration.d.ts.map +1 -1
  41. package/dist/integration.js +693 -13
  42. package/dist/integration.js.map +1 -1
  43. package/dist/local-git.d.ts +105 -8
  44. package/dist/local-git.d.ts.map +1 -1
  45. package/dist/local-git.js +155 -24
  46. package/dist/local-git.js.map +1 -1
  47. package/dist/model-provider-fixtures.d.ts +9 -1
  48. package/dist/model-provider-fixtures.d.ts.map +1 -1
  49. package/dist/observations.d.ts +7 -0
  50. package/dist/observations.d.ts.map +1 -0
  51. package/dist/polling.d.ts +1 -0
  52. package/dist/polling.d.ts.map +1 -1
  53. package/dist/process-driver.d.ts +5 -1
  54. package/dist/process-driver.d.ts.map +1 -1
  55. package/dist/process-fixtures.d.ts +56 -0
  56. package/dist/process-fixtures.d.ts.map +1 -0
  57. package/dist/process.d.ts +440 -0
  58. package/dist/process.d.ts.map +1 -0
  59. package/dist/process.js +484 -0
  60. package/dist/process.js.map +1 -0
  61. package/dist/question-fixtures.d.ts +2 -0
  62. package/dist/question-fixtures.d.ts.map +1 -1
  63. package/dist/server-extension-test-harness.d.ts +43 -3
  64. package/dist/server-extension-test-harness.d.ts.map +1 -1
  65. package/dist/stub-worker-entry.js +1 -1
  66. package/dist/supported-question-fixtures.d.ts +96 -0
  67. package/dist/supported-question-fixtures.d.ts.map +1 -0
  68. package/dist/test-capability.d.ts +9 -0
  69. package/dist/test-capability.d.ts.map +1 -0
  70. package/dist/test-diagnostics.d.ts +14 -0
  71. package/dist/test-diagnostics.d.ts.map +1 -0
  72. package/dist/worker-testing/in-process-worker-spawn.d.ts +19 -1
  73. package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -1
  74. package/dist/worker-testing/index.d.ts +6 -7
  75. package/dist/worker-testing/index.d.ts.map +1 -1
  76. package/dist/worker-testing/index.js +32 -22
  77. package/dist/worker-testing/index.js.map +1 -1
  78. package/dist/worker-testing/schema-driven-stub-pi.d.ts +5 -0
  79. package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -1
  80. package/dist/worker-testing/stub-pi-controls.d.ts +4 -0
  81. package/dist/worker-testing/stub-pi-controls.d.ts.map +1 -1
  82. package/dist/worker-testing/stub-pi-tree-handle.d.ts +78 -2
  83. package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
  84. package/dist/worker-testing/worker-runtime-harness.d.ts +37 -2
  85. package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -1
  86. package/dist/worker-testing/worker-start-payload.d.ts +17 -1
  87. package/dist/worker-testing/worker-start-payload.d.ts.map +1 -1
  88. package/package.json +14 -8
  89. package/src/compact-process-detail-fixture.ts +9 -1
  90. package/src/extension-integration-harness.ts +1059 -0
  91. package/src/fakes/fake-git-ops.ts +12 -0
  92. package/src/fakes/fake-llm.ts +11 -0
  93. package/src/fakes/index.ts +1 -1
  94. package/src/fixtures.ts +16 -0
  95. package/src/http-launch.ts +2 -1
  96. package/src/index.ts +13 -42
  97. package/src/integration-harness.ts +100 -9
  98. package/src/integration.ts +23 -9
  99. package/src/local-git.ts +196 -45
  100. package/src/model-provider-fixtures.ts +15 -2
  101. package/src/observations.ts +19 -0
  102. package/src/polling.ts +1 -0
  103. package/src/process-driver.ts +7 -1
  104. package/src/process-fixtures.ts +123 -0
  105. package/src/process.ts +768 -0
  106. package/src/question-fixtures.ts +2 -0
  107. package/src/server-extension-test-harness.ts +64 -7
  108. package/src/supported-question-fixtures.ts +168 -0
  109. package/src/test-capability.ts +9 -0
  110. package/src/test-diagnostics.ts +69 -0
  111. package/src/worker-testing/in-process-worker-spawn.ts +44 -4
  112. package/src/worker-testing/index.ts +4 -30
  113. package/src/worker-testing/schema-driven-stub-pi.ts +8 -1
  114. package/src/worker-testing/stub-pi-controls.ts +4 -0
  115. package/src/worker-testing/stub-pi-tree-handle.ts +87 -3
  116. package/src/worker-testing/worker-runtime-harness.ts +57 -6
  117. package/src/worker-testing/worker-start-payload.ts +17 -1
  118. package/dist/chunk-2IICIB6D.js.map +0 -1
  119. package/dist/chunk-3MQO3NCX.js +0 -15
  120. package/dist/chunk-3MQO3NCX.js.map +0 -1
  121. package/dist/chunk-7I4OCTF3.js.map +0 -1
  122. package/dist/chunk-7ZK5QRGP.js +0 -98
  123. package/dist/chunk-7ZK5QRGP.js.map +0 -1
  124. package/dist/chunk-JUH3LUYK.js.map +0 -1
  125. package/dist/chunk-KPSK7EMY.js.map +0 -1
  126. package/dist/chunk-MV4W6NOO.js +0 -105
  127. package/dist/chunk-MV4W6NOO.js.map +0 -1
  128. package/dist/test-app.d.ts +0 -23
  129. package/dist/test-app.d.ts.map +0 -1
  130. package/src/test-app.ts +0 -82
package/src/process.ts ADDED
@@ -0,0 +1,768 @@
1
+ import { bindExternalWrites } from "@leitwerk-dev/external-writes/internal";
2
+ import type { ExtensionTestCapability } from "./test-capability.js";
3
+
4
+ export type { ExtensionTestCapability } from "./test-capability.js";
5
+
6
+ import type {
7
+ Actor,
8
+ ProcessProject,
9
+ ProcessTurnRecord,
10
+ TurnProgressReport,
11
+ } from "@leitwerk-dev/domain";
12
+ import { setupServerExtensions } from "@leitwerk-dev/extension-runtime";
13
+ import {
14
+ buildExtensionCatalogFromModules,
15
+ buildServerProcessForTest,
16
+ buildWorkerProcessForTest,
17
+ createTestServerProcessContext,
18
+ } from "@leitwerk-dev/extension-runtime/testing";
19
+ import {
20
+ buildProcessLaunchers,
21
+ buildProcessWatchers,
22
+ coreHostCapabilities,
23
+ createCapabilityAccessor,
24
+ type ExtensionProcessDefinition,
25
+ type FormDefinition,
26
+ type IntegrationToolDefinition,
27
+ type LeitwerkExtensionModule,
28
+ type ProcessLifecycleEffects,
29
+ resolveHumanTurnView,
30
+ type ServerProcessContext,
31
+ type TicketCreationDestinationSnapshot,
32
+ toProcessGraphView,
33
+ } from "@leitwerk-dev/process-sdk";
34
+ import { observe, type TestObservation } from "./observations.js";
35
+ import { createProcessFixture, type ProcessFixtureOptions } from "./process-fixtures.js";
36
+ import { createTestServerSetupCapability } from "./server-extension-test-harness.js";
37
+
38
+ export type { TestObservation } from "./observations.js";
39
+
40
+ /** Data-only process descriptions. @public */
41
+ export interface ExtensionProcessDescription {
42
+ /** @public */
43
+ id: string;
44
+ /** @public */
45
+ entryTurnId: string;
46
+ /** @public */
47
+ entryTurnIds: string[];
48
+ /** @public */
49
+ turns: {
50
+ /** @public */
51
+ id: string;
52
+ /** @public */
53
+ kind: string;
54
+ /** @public */
55
+ description: string;
56
+ /** @public */
57
+ availableTools?: readonly string[];
58
+ /** @public */
59
+ branchType?: string;
60
+ /** @public */
61
+ context?: string;
62
+ /** @public */
63
+ restorePrimaryLeafAfterTurn?: boolean;
64
+ /** Human action descriptions, including scheduling and acceptance. @public */
65
+ humanView?: {
66
+ /** @public */
67
+ actions: readonly {
68
+ /** @public */
69
+ actionId: string;
70
+ /** @public */
71
+ acceptanceState: string;
72
+ /** @public */
73
+ label?: string;
74
+ /** @public */
75
+ description?: string;
76
+ /** @public */
77
+ scheduling?: {
78
+ /** @public */
79
+ preview: {
80
+ /** @public */
81
+ kind: string;
82
+ /** @public */
83
+ trigger?: string;
84
+ /** @public */
85
+ turnId?: string | null;
86
+ /** @public */
87
+ lifecycleStatus?: string;
88
+ };
89
+ };
90
+ }[];
91
+ };
92
+ /** @public */
93
+ startFrom?: unknown;
94
+ /** @public */
95
+ publishedProduct?: string;
96
+ /** @public */
97
+ consumedProducts?: readonly string[];
98
+ }[];
99
+ /** @public */
100
+ transitions: {
101
+ /** @public */
102
+ from: string;
103
+ /** @public */
104
+ nextTurnId?: string;
105
+ /** @public */
106
+ lifecycleStatus?: string;
107
+ /** @public */
108
+ outcome?: string;
109
+ /** @public */
110
+ trigger?: string;
111
+ }[];
112
+ /** @public */
113
+ actions: {
114
+ /** @public */
115
+ id: string;
116
+ /** @public */
117
+ label: string;
118
+ /** @public */
119
+ form?: FormDefinition;
120
+ }[];
121
+ /** @public */
122
+ launchers: {
123
+ /** @public */
124
+ id: string;
125
+ /** @public */
126
+ label: string;
127
+ /** @public */
128
+ description: string;
129
+ /** @public */
130
+ launchConfigSchema: FormDefinition;
131
+ }[];
132
+ /** @public */
133
+ watchers: {
134
+ /** @public */
135
+ id: string;
136
+ /** @public */
137
+ label: string;
138
+ /** @public */
139
+ description: string;
140
+ /** @public */
141
+ source: string;
142
+ }[];
143
+ }
144
+
145
+ /** Independent business data for each evaluation. @public */
146
+ export interface ExtensionToolFixture extends ExtensionProcessFixture {
147
+ /** Reuse an invocation identity when retrying the same external write. @public */
148
+ invocationId?: string;
149
+ /** Authorized ticket destination resolved by the owning extension. @public */
150
+ ticketDestination?: TicketCreationDestinationSnapshot;
151
+ }
152
+
153
+ /** Receipt recorded by an extension-owned external write. @public */
154
+ export interface ExtensionTestWriteReceipt {
155
+ /** @public */
156
+ instanceId: string;
157
+ /** @public */
158
+ writeType: string;
159
+ /** @public */
160
+ dedupKey: string;
161
+ /** @public */
162
+ metadata?: unknown;
163
+ }
164
+
165
+ /** Independent business data for each evaluation. @public */
166
+ export interface ExtensionProcessFixture<TParams = unknown, TState = unknown>
167
+ extends ProcessFixtureOptions<TParams, TState> {
168
+ /** @public */
169
+
170
+ projects?: readonly ProcessProject[];
171
+ /** Named product markdown available to prompts and effects. @public */
172
+ products?: Readonly<Record<string, string>>;
173
+ /** Workspace for process-owned file operations. @public */
174
+ workspaceRoot?: string;
175
+ }
176
+
177
+ /** Scripted result of one LLM invocation. @public */
178
+ export interface ExtensionTurnResponse {
179
+ /** @public */
180
+
181
+ outcome: string;
182
+
183
+ /** @public */
184
+
185
+ params?: Record<string, unknown>;
186
+
187
+ /** @public */
188
+
189
+ markdown?: string | null;
190
+ /** @public */
191
+ resultSummary?: string;
192
+ }
193
+
194
+ /** Observable effects of process-owned server behavior. @public */
195
+ export interface ExtensionProcessEffects<TState = unknown> {
196
+ /** @public */
197
+
198
+ transitions: {
199
+ /** @public */
200
+ turnId?: string | null;
201
+
202
+ /** @public */
203
+
204
+ lifecycleStatus?: string;
205
+
206
+ /** @public */
207
+
208
+ state?: TState;
209
+
210
+ /** @public */
211
+
212
+ trigger?: string;
213
+ }[];
214
+
215
+ /** @public */
216
+
217
+ inputs: {
218
+ /** @public */
219
+ source: string;
220
+
221
+ /** @public */
222
+
223
+ kind: string;
224
+
225
+ /** @public */
226
+
227
+ bodyMarkdown: string;
228
+
229
+ /** @public */
230
+
231
+ target?: unknown;
232
+ }[];
233
+
234
+ /** @public */
235
+
236
+ events: {
237
+ /** @public */
238
+ type: string;
239
+
240
+ /** @public */
241
+ data: unknown;
242
+ }[];
243
+
244
+ /** @public */
245
+
246
+ lifecycle: ProcessLifecycleEffects[];
247
+ }
248
+
249
+ /** Extension registration inputs; adapters remain owned by their extensions. @public */
250
+ export interface ExtensionTestHarnessOptions {
251
+ /** Configuration keyed by extension manifest id. @public */
252
+ extensionConfig?: Readonly<Record<string, unknown>>;
253
+ /** @public */
254
+
255
+ extensions?: readonly LeitwerkExtensionModule[];
256
+
257
+ /** @public */
258
+
259
+ capabilities?: readonly ExtensionTestCapability[];
260
+ }
261
+
262
+ /** Evaluate registered behavior without a database or worker. @public */
263
+ export async function createExtensionTestHarness(options: ExtensionTestHarnessOptions = {}) {
264
+ const catalog = await buildExtensionCatalogFromModules(options.extensions ?? []);
265
+ const receipts: ExtensionTestWriteReceipt[] = [];
266
+ const externalWrites = {
267
+ hasDedupKey: (key: string) => receipts.some((receipt) => receipt.dedupKey === key),
268
+ record(input: ExtensionTestWriteReceipt) {
269
+ const receipt = structuredClone(input);
270
+ receipts.push(receipt);
271
+ return receipt;
272
+ },
273
+ };
274
+ const capabilities = createCapabilityAccessor([
275
+ {
276
+ token: coreHostCapabilities.serverSetup,
277
+ value: createTestServerSetupCapability({ externalWrites }),
278
+ },
279
+ ...(options.capabilities ?? []),
280
+ ]);
281
+ const tools = new Map<string, IntegrationToolDefinition<unknown>>();
282
+ const starts: (() => void | Promise<void>)[] = [];
283
+ const stops: (() => void | Promise<void>)[] = [];
284
+ const listeners = new Map<string, Set<(event: never) => void | Promise<void>>>();
285
+ const pendingEvents = new Set<Promise<void>>();
286
+ const eventErrors: unknown[] = [];
287
+ let toolSequence = 0;
288
+ function emit(type: string, event: unknown) {
289
+ for (const listener of listeners.get(type) ?? []) {
290
+ const task = Promise.resolve()
291
+ .then(() => listener(structuredClone(event) as never))
292
+ .catch((error) => {
293
+ eventErrors.push(error);
294
+ })
295
+ .finally(() => pendingEvents.delete(task));
296
+ pendingEvents.add(task);
297
+ }
298
+ }
299
+ async function drainEvents() {
300
+ let timer: ReturnType<typeof setTimeout> | undefined;
301
+ try {
302
+ await Promise.race([
303
+ (async () => {
304
+ while (pendingEvents.size) await Promise.all([...pendingEvents]);
305
+ })(),
306
+ new Promise<never>((_resolve, reject) => {
307
+ timer = setTimeout(
308
+ () => reject(new Error("Extension event handlers did not settle within 12 seconds")),
309
+ 12000,
310
+ );
311
+ }),
312
+ ]);
313
+ } finally {
314
+ clearTimeout(timer);
315
+ }
316
+ if (eventErrors.length)
317
+ throw new AggregateError(eventErrors.splice(0), "Extension event handler failed");
318
+ }
319
+ let closed = false;
320
+ function assertOpen() {
321
+ if (closed) throw new Error("Extension test harness is closed");
322
+ }
323
+ /** @public */
324
+ async function close() {
325
+ if (closed) return;
326
+ closed = true;
327
+ const failures: unknown[] = [];
328
+ for (const stop of stops.reverse()) {
329
+ try {
330
+ await stop();
331
+ } catch (error) {
332
+ failures.push(error);
333
+ }
334
+ }
335
+ listeners.clear();
336
+ try {
337
+ await drainEvents();
338
+ } catch (error) {
339
+ failures.push(error);
340
+ }
341
+ if (failures.length) throw new AggregateError(failures, "Extension cleanup failed");
342
+ }
343
+ try {
344
+ await setupServerExtensions(
345
+ catalog,
346
+ {
347
+ provide: capabilities.provide.bind(capabilities),
348
+ get: capabilities.get.bind(capabilities),
349
+ require: capabilities.require.bind(capabilities),
350
+ tool(tool) {
351
+ if (tools.has(tool.name)) throw new Error(`Duplicate integration tool '${tool.name}'`);
352
+ tools.set(tool.name, tool as IntegrationToolDefinition<unknown>);
353
+ },
354
+ events: {
355
+ on(type, listener) {
356
+ const set = listeners.get(type) ?? new Set();
357
+ set.add(listener);
358
+ listeners.set(type, set);
359
+ },
360
+ off(type, listener) {
361
+ listeners.get(type)?.delete(listener);
362
+ },
363
+ emit,
364
+ },
365
+ onStart: (hook) => {
366
+ starts.push(hook);
367
+ },
368
+ onStop: (hook) => {
369
+ stops.push(hook);
370
+ },
371
+ },
372
+ (id) => structuredClone(options.extensionConfig?.[id] ?? {}),
373
+ );
374
+ for (const start of starts) await start();
375
+ await drainEvents();
376
+ } catch (error) {
377
+ await close().catch(() => {});
378
+ throw error;
379
+ }
380
+
381
+ /** @public */
382
+ async function callTool(
383
+ name: string,
384
+ args: Record<string, unknown>,
385
+ fixture: ExtensionToolFixture = {},
386
+ ) {
387
+ assertOpen();
388
+ const tool = tools.get(name);
389
+ if (!tool) throw new Error(`Unknown integration tool '${name}'`);
390
+ const process = createProcessFixture(fixture);
391
+ const projects = structuredClone([...(fixture.projects ?? [])]);
392
+ for (const project of projects)
393
+ if (project.instanceId !== process.id) throw new Error("Project belongs to another process");
394
+ const turn: ProcessTurnRecord = {
395
+ id: "trn_test",
396
+ instanceId: process.id,
397
+ turnId: process.selectedTurnId ?? "test_turn",
398
+ turnType: "automatic",
399
+ status: "running",
400
+ attemptNumber: 1,
401
+ parentTurnRecordId: null,
402
+ pathType: "primary",
403
+ forkPiEntryId: null,
404
+ resultPiEntryId: null,
405
+ modelProfileId: null,
406
+ turnResultMarkdown: null,
407
+ errorSummary: null,
408
+ errorClass: null,
409
+ startedAt: process.createdAt,
410
+ endedAt: null,
411
+ };
412
+ return observe(
413
+ await tool.execute(
414
+ {
415
+ process,
416
+ projects,
417
+ turn,
418
+ project:
419
+ projects.find((project) => project.key === args.projectKey) ??
420
+ (projects.length === 1 ? (projects[0] ?? null) : null),
421
+ idempotencyKey: fixture.invocationId ?? `${process.id}:test_tool:${++toolSequence}`,
422
+ ticketDestination: structuredClone(fixture.ticketDestination),
423
+ externalWrites: bindExternalWrites(externalWrites, process.id),
424
+ signal: new AbortController().signal,
425
+ },
426
+ tool.parse ? tool.parse(structuredClone(args)) : structuredClone(args),
427
+ ),
428
+ );
429
+ }
430
+
431
+ function destinationProvider(name: string) {
432
+ assertOpen();
433
+ const provider = tools.get(name)?.capability?.destinations;
434
+ if (!provider) throw new Error(`Tool '${name}' has no ticket destinations`);
435
+ return provider;
436
+ }
437
+ return {
438
+ /** List destinations through the registered tool capability. @public */
439
+ async listToolDestinations(name: string, actor: Actor) {
440
+ return observe(await destinationProvider(name).list({ actor: structuredClone(actor) }));
441
+ },
442
+ /** Resolve an authorized destination snapshot. @public */
443
+ async resolveToolDestination(name: string, destinationId: string, actor: Actor) {
444
+ return observe(
445
+ await destinationProvider(name).resolve({ actor: structuredClone(actor), destinationId }),
446
+ );
447
+ },
448
+ /** Validate a saved destination against the provider. @public */
449
+ async validateToolDestination(name: string, snapshot: TicketCreationDestinationSnapshot) {
450
+ await destinationProvider(name).validate(structuredClone(snapshot));
451
+ },
452
+ /** Detached descriptions of registered tools. @public */
453
+ describeTools() {
454
+ assertOpen();
455
+ return observe(
456
+ [...tools.values()].map(({ name, description, parameters }) => ({
457
+ /** @public */
458
+ name,
459
+ /** @public */
460
+ description,
461
+ /** @public */
462
+ parameters,
463
+ })),
464
+ );
465
+ },
466
+ /** Detached receipts, including writes recorded before an invocation failed. @public */
467
+ writeReceipts() {
468
+ assertOpen();
469
+ return observe(receipts);
470
+ },
471
+ /** Run an integration tool registered by an extension. @public */
472
+ callTool,
473
+ /** Deliver an event and await its registered handlers. @public */
474
+ async emit(type: string, event: unknown) {
475
+ assertOpen();
476
+ emit(type, event);
477
+ await drainEvents();
478
+ },
479
+ /** Run cleanup hooks once, including when another hook fails. @public */
480
+ close,
481
+ /** Bind a definition and independent default fixtures. @public */
482
+ process<TParams, TState>(
483
+ definition: ExtensionProcessDefinition<TParams, TState>,
484
+ initial: ExtensionProcessFixture<TParams, TState> = {},
485
+ ) {
486
+ assertOpen();
487
+ const defaults = structuredClone(initial);
488
+ const worker = buildWorkerProcessForTest(definition);
489
+ const server = buildServerProcessForTest(definition);
490
+ const launchers = buildProcessLaunchers(definition)?.launchers;
491
+ const watchers = buildProcessWatchers(definition)?.watchers;
492
+ function context(fixture: ExtensionProcessFixture<TParams, TState> = {}) {
493
+ assertOpen();
494
+ const input = structuredClone({ ...defaults, ...fixture });
495
+ const process = createProcessFixture(input, definition);
496
+ const projects = input.projects ?? [];
497
+ for (const project of projects)
498
+ if (project.instanceId !== process.id)
499
+ throw new Error("Project belongs to another process");
500
+ return {
501
+ process,
502
+ projects,
503
+ params: definition.paramsCodec.parse(JSON.parse(process.paramsJson ?? "null")),
504
+ state: definition.stateCodec.parse(JSON.parse(process.stateJson ?? "null")),
505
+ turnResultMarkdownByProduct: input.products,
506
+ workspaceRoot: input.workspaceRoot,
507
+ };
508
+ }
509
+ function effects(fixture?: ExtensionProcessFixture<TParams, TState>) {
510
+ const base = context(fixture);
511
+ const result: ExtensionProcessEffects<TState> = {
512
+ transitions: [],
513
+ inputs: [],
514
+ events: [],
515
+ lifecycle: [],
516
+ };
517
+ const ctx = createTestServerProcessContext({
518
+ ...base,
519
+ transition: async (next) => {
520
+ result.transitions.push(structuredClone(next));
521
+ },
522
+ queueInput: (input) => {
523
+ result.inputs.push(structuredClone(input));
524
+ },
525
+ emitEvent: (type, data) => {
526
+ result.events.push({ type, data: structuredClone(data) });
527
+ },
528
+ applyLifecycleEffects: (effect) => {
529
+ result.lifecycle.push(structuredClone(effect));
530
+ },
531
+ readProductTurnResultMarkdown: (name) => base.turnResultMarkdownByProduct?.[name] ?? null,
532
+ readSemanticTurnResultMarkdown: (name) =>
533
+ base.turnResultMarkdownByProduct?.[name] ?? null,
534
+ });
535
+ return { ctx, result };
536
+ }
537
+ context();
538
+ return {
539
+ /** Return data descriptions without exposing registered handlers. @public */
540
+ describe(): TestObservation<ExtensionProcessDescription> {
541
+ assertOpen();
542
+ return observe({
543
+ /** @public */
544
+ id: definition.id,
545
+ /** @public */
546
+ entryTurnId: definition.entryTurnId,
547
+ entryTurnIds: [definition.entryTurnId, ...(definition.alternateEntryTurnIds ?? [])],
548
+ /** @public */
549
+ turns: [...definition.turns].map(([id, binding]) => ({
550
+ id,
551
+ kind: binding.definition.kind,
552
+ description: binding.definition.description,
553
+ ...(binding.definition.kind === "llm"
554
+ ? {
555
+ availableTools: binding.definition.availableTools,
556
+ branchType: binding.definition.branchType,
557
+ context: binding.definition.context,
558
+ restorePrimaryLeafAfterTurn: binding.definition.restorePrimaryLeafAfterTurn,
559
+ startFrom: binding.definition.startFrom,
560
+ publishedProduct: binding.definition.publishedProduct,
561
+ consumedProducts: binding.definition.consumedProducts,
562
+ }
563
+ : binding.definition.kind === "human"
564
+ ? { humanView: resolveHumanTurnView({ turnId: id, turn: binding.definition }) }
565
+ : {}),
566
+ })),
567
+ /** @public */
568
+ transitions: [
569
+ ...toProcessGraphView(definition as ExtensionProcessDefinition).turns,
570
+ ].flatMap(([from, turn]) =>
571
+ turn.transitions.map((transition) => ({ from, ...transition })),
572
+ ),
573
+ /** @public */
574
+ actions: [...(server?.actions.values() ?? [])].map((a) => ({
575
+ /** @public */
576
+ id: a.id,
577
+ label: a.label,
578
+ form: a.form,
579
+ })),
580
+ /** @public */
581
+ launchers: [...(launchers?.values() ?? [])].map((a) => ({
582
+ /** @public */
583
+ id: a.id,
584
+ label: a.label,
585
+ description: a.description,
586
+ launchConfigSchema: a.ui.launchConfigSchema as FormDefinition,
587
+ })),
588
+ /** @public */
589
+ watchers: [...(watchers?.values() ?? [])].map((a) => ({
590
+ /** @public */
591
+ id: a.id,
592
+ label: a.label,
593
+ description: a.description,
594
+ source: a.source.id,
595
+ })),
596
+ });
597
+ },
598
+ /** Resolve a UI launcher using its own validation. @public */
599
+ async resolveLaunch(id: string, input: Record<string, unknown>) {
600
+ const ctx = context();
601
+ const launcher = launchers?.get(id);
602
+ if (!launcher) throw new Error(`Unknown launcher '${id}'`);
603
+ return observe(await launcher.ui.resolveLaunchConfig(structuredClone(input), ctx));
604
+ },
605
+ /** Prepare persisted launcher input for a new launch. @public */
606
+ async prepareRelaunch(id: string, previousInput: Record<string, unknown>) {
607
+ const ctx = context();
608
+ const launcher = launchers?.get(id);
609
+ if (!launcher) throw new Error(`Unknown launcher '${id}'`);
610
+ return observe(
611
+ (await launcher.ui.resolveRelaunchInput?.(structuredClone(previousInput), ctx)) ??
612
+ previousInput,
613
+ );
614
+ },
615
+ /** Parse source configuration and resolve a matching watcher event. @public */
616
+ async resolveWatcherLaunch(id: string, event: unknown, config: unknown) {
617
+ const ctx = context();
618
+ const watcher = watchers?.get(id);
619
+ if (!watcher) throw new Error(`Unknown watcher '${id}'`);
620
+ const parsed = watcher.source.parseConfig(structuredClone(config));
621
+ if (
622
+ !parsed.enabled ||
623
+ (watcher.matches && !(await watcher.matches(structuredClone(event), ctx)))
624
+ )
625
+ return null;
626
+ return observe(await watcher.resolveLaunchConfig(structuredClone(event), ctx));
627
+ },
628
+ /** Run preparation, prompt evaluation, and the registered worker handler. @public */
629
+ async evaluateTurn(
630
+ id: string,
631
+ options: {
632
+ /** @public */
633
+ responses?: readonly ExtensionTurnResponse[];
634
+
635
+ /** @public */
636
+
637
+ fixture?: ExtensionProcessFixture<TParams, TState>;
638
+ } = {},
639
+ ) {
640
+ const binding = definition.turns.get(id);
641
+ const handler = worker?.turns.get(id);
642
+ if (!binding || !handler) throw new Error(`Unknown worker turn '${id}'`);
643
+ const base = context({
644
+ ...options.fixture,
645
+ position: { selectedTurnId: id, lifecycleStatus: "active" },
646
+ });
647
+ const prompts: string[] = [];
648
+ const tools: { name: string; arguments: Record<string, unknown> }[] = [];
649
+ const progress: TurnProgressReport[] = [];
650
+ const completed: ExtensionTurnResponse[] = [];
651
+ const requestedTools = new Set<string>();
652
+ const parked: (string | undefined)[] = [];
653
+ const responses = structuredClone([...(options.responses ?? [])]);
654
+ const ctx = {
655
+ ...base,
656
+ async callIntegrationTool(name: string, args: Record<string, unknown>) {
657
+ const def = binding.definition;
658
+ const allowed =
659
+ def.kind === "llm"
660
+ ? (def.resolveIntegrationTools?.(base.params, base.state) ?? def.integrationTools)
661
+ : def.kind === "automatic"
662
+ ? def.integrationTools
663
+ : [];
664
+ if (!allowed?.includes(name))
665
+ throw new Error(`Integration tool '${name}' is not declared for '${id}'`);
666
+ tools.push({ name, arguments: structuredClone(args) });
667
+ return callTool(name, args, {
668
+ ...defaults,
669
+ ...options.fixture,
670
+ processId: definition.id,
671
+ params: base.params,
672
+ state: base.state,
673
+ position: { selectedTurnId: id, lifecycleStatus: "active" },
674
+ });
675
+ },
676
+ reportProgress: (report: TurnProgressReport) => {
677
+ progress.push(structuredClone(report));
678
+ },
679
+ };
680
+ await handler({
681
+ ctx,
682
+ async turn(def) {
683
+ for (const name of [
684
+ ...def.availableTools,
685
+ ...Object.keys(def.outcomes ?? {}),
686
+ ...(def.resolveIntegrationTools?.(base.params, base.state) ??
687
+ def.integrationTools ??
688
+ []),
689
+ ...(def.askQuestions ? ["ask_questions"] : []),
690
+ ])
691
+ requestedTools.add(name);
692
+ const prepared = await def.prepare?.({
693
+ ...ctx,
694
+ callIntegrationTool: ctx.callIntegrationTool,
695
+ reportProgress: ctx.reportProgress,
696
+ });
697
+ prompts.push(await def.prompt({ ...ctx, prepared }));
698
+ const response = responses.shift();
699
+ if (!response)
700
+ throw new Error(
701
+ `Script exhausted while evaluating '${definition.id}/${id}' after ${prompts.length} prompt(s)`,
702
+ );
703
+ if (
704
+ def.turnEnd?.outcome !== response.outcome &&
705
+ !Object.hasOwn(def.outcomes ?? {}, response.outcome)
706
+ )
707
+ throw new Error(`Undeclared outcome '${response.outcome}' for '${id}'`);
708
+ completed.push(response);
709
+ return { outcome: response.outcome as never, params: response.params ?? {} };
710
+ },
711
+ async complete(input) {
712
+ completed.push(structuredClone(input));
713
+ },
714
+ park(reason) {
715
+ parked.push(reason);
716
+ },
717
+ });
718
+ return observe({
719
+ prompts,
720
+ tools,
721
+ requestedTools: [...requestedTools],
722
+ progress,
723
+ completed,
724
+ parked,
725
+ });
726
+ },
727
+ /** Evaluate a process action and collect its requested effects. @public */
728
+ async evaluateAction(
729
+ id: string,
730
+ input: Record<string, unknown> = {},
731
+ fixture?: ExtensionProcessFixture<TParams, TState>,
732
+ ): Promise<TestObservation<ExtensionProcessEffects<TState>>> {
733
+ const action = server?.actions.get(id);
734
+ if (!action) throw new Error(`Unknown action '${id}'`);
735
+ const { ctx, result } = effects(fixture);
736
+ await action.plan?.(structuredClone(input), ctx);
737
+ await action.execute?.(structuredClone(input), ctx);
738
+ return observe(result);
739
+ },
740
+ /** Evaluate process-owned outcome handling against fresh business data. @public */
741
+ async evaluateOutcome(
742
+ id: string,
743
+ outcome: ExtensionTurnResponse,
744
+ fixture?: ExtensionProcessFixture<TParams, TState>,
745
+ ): Promise<TestObservation<ExtensionProcessEffects<TState>>> {
746
+ if (!definition.turns.has(id)) throw new Error(`Undeclared turn '${id}'`);
747
+ const { ctx, result } = effects({
748
+ ...fixture,
749
+ position: fixture?.position ??
750
+ defaults.position ?? { selectedTurnId: id, lifecycleStatus: "active" },
751
+ });
752
+ for (const handler of server?.turnOutcomeHandlers.get(id) ?? [])
753
+ await handler(
754
+ {
755
+ turnId: id,
756
+ turnRecordId: "trn_test",
757
+ outcome: outcome.outcome,
758
+ params: structuredClone(outcome.params ?? {}),
759
+ turnResultMarkdown: outcome.markdown,
760
+ },
761
+ ctx as ServerProcessContext<TParams, TState>,
762
+ );
763
+ return observe(result);
764
+ },
765
+ };
766
+ },
767
+ };
768
+ }