@leitwerk-dev/test-support 0.2.1 → 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 (59) hide show
  1. package/dist/{chunk-ECAWLVYB.js → chunk-E4Y7XND5.js} +3 -1
  2. package/dist/chunk-E4Y7XND5.js.map +1 -0
  3. package/dist/chunk-KJVNI2UP.js +17 -0
  4. package/dist/chunk-KJVNI2UP.js.map +1 -0
  5. package/dist/{chunk-2PCDTYVH.js → chunk-OE4NHDVS.js} +10 -4
  6. package/dist/chunk-OE4NHDVS.js.map +1 -0
  7. package/dist/chunk-P2FF4AP7.js +72 -0
  8. package/dist/chunk-P2FF4AP7.js.map +1 -0
  9. package/dist/chunk-RY6Y6V5E.js +54 -0
  10. package/dist/chunk-RY6Y6V5E.js.map +1 -0
  11. package/dist/extension-integration-harness.d.ts +357 -0
  12. package/dist/extension-integration-harness.d.ts.map +1 -0
  13. package/dist/fixtures.d.ts +2 -0
  14. package/dist/fixtures.d.ts.map +1 -1
  15. package/dist/fixtures.js +53 -0
  16. package/dist/fixtures.js.map +1 -1
  17. package/dist/index.d.ts +2 -19
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +4 -67
  20. package/dist/index.js.map +1 -1
  21. package/dist/integration.d.ts +1 -0
  22. package/dist/integration.d.ts.map +1 -1
  23. package/dist/integration.js +564 -2
  24. package/dist/integration.js.map +1 -1
  25. package/dist/local-git.d.ts.map +1 -1
  26. package/dist/local-git.js.map +1 -1
  27. package/dist/observations.d.ts +7 -0
  28. package/dist/observations.d.ts.map +1 -0
  29. package/dist/process-fixtures.d.ts +56 -0
  30. package/dist/process-fixtures.d.ts.map +1 -0
  31. package/dist/process.d.ts +440 -0
  32. package/dist/process.d.ts.map +1 -0
  33. package/dist/process.js +484 -0
  34. package/dist/process.js.map +1 -0
  35. package/dist/stub-worker-entry.js +1 -1
  36. package/dist/supported-question-fixtures.d.ts +96 -0
  37. package/dist/supported-question-fixtures.d.ts.map +1 -0
  38. package/dist/test-capability.d.ts +9 -0
  39. package/dist/test-capability.d.ts.map +1 -0
  40. package/dist/worker-testing/in-process-worker-spawn.d.ts +2 -0
  41. package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -1
  42. package/dist/worker-testing/index.js +2 -2
  43. package/dist/worker-testing/stub-pi-tree-handle.d.ts +2 -0
  44. package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
  45. package/package.json +14 -9
  46. package/src/extension-integration-harness.ts +1059 -0
  47. package/src/fixtures.ts +16 -0
  48. package/src/index.ts +4 -19
  49. package/src/integration.ts +21 -0
  50. package/src/local-git.ts +1 -0
  51. package/src/observations.ts +19 -0
  52. package/src/process-fixtures.ts +123 -0
  53. package/src/process.ts +768 -0
  54. package/src/supported-question-fixtures.ts +168 -0
  55. package/src/test-capability.ts +9 -0
  56. package/src/worker-testing/in-process-worker-spawn.ts +15 -2
  57. package/src/worker-testing/stub-pi-tree-handle.ts +5 -0
  58. package/dist/chunk-2PCDTYVH.js.map +0 -1
  59. package/dist/chunk-ECAWLVYB.js.map +0 -1
@@ -0,0 +1,1059 @@
1
+ import type { ExtensionTestCapability } from "./test-capability.js";
2
+
3
+ export type { ExtensionTestCapability } from "./test-capability.js";
4
+
5
+ import { randomUUID } from "node:crypto";
6
+ import { mkdirSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import type {
9
+ Actor,
10
+ ExternalWriteLog,
11
+ ProcessInstance,
12
+ ProcessProject,
13
+ ProcessTurnRecord,
14
+ } from "@leitwerk-dev/domain";
15
+ import { buildExtensionCatalogFromModules } from "@leitwerk-dev/extension-runtime/testing";
16
+ import {
17
+ coreHostCapabilities,
18
+ type ExtensionProcessDefinition,
19
+ type LeitwerkExtensionModule,
20
+ } from "@leitwerk-dev/process-sdk";
21
+ import { createAcceptedLlmTurn, prepareAcceptedFixtureStart } from "@leitwerk-dev/server/testing";
22
+ import { postImmediateLaunch } from "./http-launch.js";
23
+ import { createPersistentIntegrationFixture } from "./integration-harness.js";
24
+ import { observe, type TestObservation } from "./observations.js";
25
+ import { createProcessFixture, type ProcessFixtureOptions } from "./process-fixtures.js";
26
+ import type { QuestionRequestFixture } from "./supported-question-fixtures.js";
27
+ import { StubPiTreeHandleFactory } from "./worker-testing/stub-pi-tree-handle.js";
28
+
29
+ /** Model-visible inputs for a scripted invocation. @public */
30
+ export interface IntegrationPromptObservation {
31
+ /** @public */
32
+ turnId: string;
33
+ /** Working directory available for fixture repository edits. @public */
34
+ cwd: string;
35
+ /** Opaque branch-session identity for comparing execution relationships. @public */
36
+ branchId: string;
37
+ /** Text inherited by the current branch. @public */
38
+ history: string;
39
+ /** @public */
40
+ tools: readonly {
41
+ /** @public */
42
+ name: string;
43
+ /** @public */
44
+ parameters: Record<string, unknown>;
45
+ }[];
46
+ }
47
+
48
+ /** Rendered result retained at a tree leaf. @public */
49
+ export interface IntegrationLeafObservation {
50
+ /** @public */
51
+ id: string;
52
+ /** @public */
53
+ instanceId: string;
54
+ /** @public */
55
+ leafEntryId: string;
56
+ /** @public */
57
+ turnRecordId: string | null;
58
+ /** @public */
59
+ rendererId: string | null;
60
+ /** @public */
61
+ schemaVersion: number | null;
62
+ /** @public */
63
+ props: Record<string, unknown> | null;
64
+ /** @public */
65
+ fallbackMarkdown: string | null;
66
+ /** @public */
67
+ status: "ready" | "capture_error";
68
+ }
69
+
70
+ /** Recorded semantic event. @public */
71
+ export interface IntegrationEventObservation {
72
+ /** @public */
73
+ id: string;
74
+ /** @public */
75
+ eventType: string;
76
+ /** @public */
77
+ data: Record<string, unknown>;
78
+ /** @public */
79
+ createdAt: string;
80
+ }
81
+
82
+ /** Durable annotation of process execution. @public */
83
+ export interface IntegrationAnnotationObservation {
84
+ /** @public */
85
+ id: string;
86
+ /** @public */
87
+ annotationType: string;
88
+ /** @public */
89
+ payload: Record<string, unknown>;
90
+ }
91
+
92
+ /** One scripted model prompt, executed through registered tools. @public */
93
+ export interface IntegrationTurnScript {
94
+ /** @public */
95
+ tools: readonly IntegrationToolCall[];
96
+ /** Scripted reasoning retained by the normal worker path. @public */
97
+ thinking?: readonly string[];
98
+ /** Assistant markdown for turns completed by model output. @public */
99
+ markdown?: string;
100
+ /** Optional model response after an integration-tool result. @public */
101
+ afterToolResult?(call: IntegrationToolCall, result: unknown): IntegrationToolCall | undefined;
102
+ }
103
+
104
+ /** @public */
105
+ export interface IntegrationToolCall {
106
+ /** @public */
107
+ name: string;
108
+ /** @public */
109
+ arguments: Record<string, unknown>;
110
+ }
111
+
112
+ /** Instruction delivered through the application's durable input queue. @public */
113
+ export interface IntegrationProcessInput {
114
+ /** @public */
115
+ bodyMarkdown: string;
116
+ /** Target a published product branch. @public */
117
+ product?: string;
118
+ }
119
+
120
+ /** Durable instruction delivery observations. @public */
121
+ export interface IntegrationInputObservation {
122
+ /** @public */
123
+ id: string;
124
+ /** @public */
125
+ instanceId: string;
126
+ /** @public */
127
+ sequence: number;
128
+ /** @public */
129
+ source: string;
130
+ /** @public */
131
+ kind: string;
132
+ /** @public */
133
+ bodyMarkdown: string;
134
+ /** @public */
135
+ target: {
136
+ /** @public */
137
+ productName?: string;
138
+ /** @public */
139
+ semanticRef?: string;
140
+ } | null;
141
+ /** @public */
142
+ actor: Actor;
143
+ /** @public */
144
+ receivedAt: string;
145
+ /** @public */
146
+ consumedAt: string | null;
147
+ }
148
+
149
+ /** Operator approval observations. @public */
150
+ export interface IntegrationApprovalObservation {
151
+ /** @public */
152
+ id: string;
153
+ /** @public */
154
+ instanceId: string;
155
+ /** @public */
156
+ turnRecordId: string;
157
+ /** @public */
158
+ toolCallId: string;
159
+ /** @public */
160
+ toolName: string;
161
+ /** @public */
162
+ arguments: Record<string, unknown>;
163
+ /** @public */
164
+ destination: {
165
+ /** @public */
166
+ id: string;
167
+ /** @public */
168
+ displayName: string;
169
+ /** @public */
170
+ group?: string;
171
+ /** @public */
172
+ description?: string;
173
+ } | null;
174
+ /** @public */
175
+ status: "open" | "accepted" | "feedback" | "declined" | "cancelled";
176
+ /** @public */
177
+ requestedAt: string;
178
+ /** @public */
179
+ resolvedAt: string | null;
180
+ /** @public */
181
+ resolvedBy: Actor | null;
182
+ /** @public */
183
+ feedback: string | null;
184
+ }
185
+
186
+ /** Explicit accepted execution setup, independent of process business state. @public */
187
+ export interface AcceptedTurnFixture {
188
+ /** @public */
189
+ turnId: string;
190
+ /** @public */
191
+ execution:
192
+ | {
193
+ /** @public */
194
+ status: "running";
195
+ }
196
+ | {
197
+ /** @public */
198
+ status: "succeeded";
199
+ /** @public */
200
+ outcome: string;
201
+ /** @public */
202
+ markdown: string;
203
+ };
204
+ }
205
+
206
+ /** Detached durable observations. @public */
207
+ export interface ExtensionIntegrationSnapshot {
208
+ /** Harness-owned process workspace. @public */
209
+ workspaceRoot: string;
210
+ /** @public */
211
+ events: IntegrationEventObservation[];
212
+ /** @public */
213
+ annotations: IntegrationAnnotationObservation[];
214
+ /** @public */
215
+ leafOutcomes: IntegrationLeafObservation[];
216
+
217
+ /** @public */
218
+ process: ProcessInstance;
219
+ /** @public */
220
+ params: unknown;
221
+ /** @public */
222
+ state: unknown;
223
+ /** @public */
224
+ projects: ProcessProject[];
225
+ /** @public */
226
+ turns: ProcessTurnRecord[];
227
+ /** @public */
228
+ inputs: IntegrationInputObservation[];
229
+ /** @public */
230
+ questions: QuestionRequestFixture[];
231
+ /** @public */
232
+ approvals: IntegrationApprovalObservation[];
233
+ /** @public */
234
+ writeReceipts: ExternalWriteLog[];
235
+ }
236
+
237
+ /** @public */
238
+ export interface ExtensionIntegrationHarnessOptions {
239
+ /** Per-process watcher configuration. @public */
240
+ watchers?: Readonly<Record<string, Record<string, unknown>>>;
241
+ /** Advance extension provider pollers explicitly in tests. @public */
242
+ polling?: "automatic" | "manual";
243
+ /** Host Docker boundary for extensions which require it. @public */
244
+ hostDocker?: {
245
+ /** @public */
246
+ preflight(timeoutMs: number): Promise<void>;
247
+ };
248
+
249
+ /** Configuration keyed by extension manifest id. @public */
250
+ extensionConfig?: Readonly<Record<string, unknown>>;
251
+ /** @public */
252
+ extensions: readonly LeitwerkExtensionModule[];
253
+ /** @public */
254
+ capabilities?: readonly ExtensionTestCapability[];
255
+ /** Automatic execution starts admitted work immediately. @public */
256
+ execution?: "automatic" | "manual";
257
+ /** Model catalog used by the supplied provider extensions. @public */
258
+ models?: readonly {
259
+ /** @public */
260
+ id: string;
261
+ /** @public */
262
+ provider: string;
263
+ /** @public */
264
+ modelId: string;
265
+ /** @public */
266
+ thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
267
+ }[];
268
+ /** Default model profile for all registered processes. @public */
269
+ defaultModel?: string;
270
+ /** Model scripts for automatic execution, in prompt order per process. @public */
271
+ script?(
272
+ instanceId: string,
273
+ prompt: string,
274
+ observation: TestObservation<IntegrationPromptObservation>,
275
+ ): IntegrationTurnScript | Promise<IntegrationTurnScript>;
276
+ }
277
+
278
+ /** HTTP-shaped requests without a Fastify handle. @public */
279
+ export interface ExtensionTestRequest {
280
+ /** @public */
281
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
282
+ /** @public */
283
+ url: string;
284
+ /** @public */
285
+ payload?: Record<string, unknown>;
286
+ /** @public */
287
+ headers?: Record<string, string>;
288
+ }
289
+
290
+ /** HTTP response observation. @public */
291
+ export interface ExtensionTestResponse {
292
+ /** @public */
293
+ statusCode: number;
294
+ /** @public */
295
+ body: string;
296
+ /** @public */
297
+ json<T = unknown>(): T;
298
+ }
299
+
300
+ /** Accepted turn identity and optional retained result. @public */
301
+ export interface AcceptedTurnReference {
302
+ /** @public */
303
+ id: string;
304
+ /** @public */
305
+ instanceId: string;
306
+ /** @public */
307
+ turnId: string;
308
+ /** @public */
309
+ artifact: {
310
+ /** @public */ kind: "turn_result";
311
+ /** @public */
312
+ turnRecordId: string;
313
+ } | null;
314
+ }
315
+
316
+ /** One durably settled worker execution. @public */
317
+ export interface IntegrationTurnResult {
318
+ /** @public */
319
+ turn: ProcessTurnRecord | null;
320
+ /** @public */
321
+ outcome: string | null;
322
+ /** @public */
323
+ failure: string | null;
324
+ /** @public */
325
+ prompts: string[];
326
+ /** @public */
327
+ toolResults: {
328
+ /** @public */ name: string;
329
+ /** @public */
330
+ result: unknown;
331
+ }[];
332
+ /** @public */
333
+ result: AcceptedTurnReference["artifact"];
334
+ }
335
+
336
+ /** Durable process commands and observations. @public */
337
+ export interface ExtensionIntegrationProcess {
338
+ /** @public */
339
+ readonly id: string;
340
+ /** @public */
341
+ seedAcceptedTurn(fixture: AcceptedTurnFixture): Promise<TestObservation<AcceptedTurnReference>>;
342
+ /** @public */
343
+ snapshot(): TestObservation<ExtensionIntegrationSnapshot>;
344
+ /** @public */
345
+ waitFor(
346
+ condition: (snapshot: TestObservation<ExtensionIntegrationSnapshot>) => boolean,
347
+ options?: {
348
+ /** @public */ timeoutMs?: number;
349
+ /** @public */
350
+ description?: string;
351
+ },
352
+ ): Promise<TestObservation<ExtensionIntegrationSnapshot>>;
353
+ /** @public */
354
+ runTurn(script?: IntegrationTurnScript): Promise<TestObservation<IntegrationTurnResult>>;
355
+ /** @public */
356
+ action(id: string, input?: Record<string, unknown>): Promise<ExtensionTestResponse>;
357
+ /** @public */
358
+ retry(): Promise<ExtensionTestResponse>;
359
+ /** @public */
360
+ supplyInput(
361
+ input: IntegrationProcessInput,
362
+ ): Promise<TestObservation<ExtensionIntegrationSnapshot>>;
363
+ /** @public */
364
+ answerQuestions(
365
+ id: string,
366
+ answers: readonly {
367
+ /** @public */
368
+ selectedOptionIds: readonly string[];
369
+ /** @public */
370
+ freeText: string;
371
+ /** @public */
372
+ comment: string;
373
+ }[],
374
+ ): Promise<ExtensionTestResponse>;
375
+ /** @public */
376
+ respondToApproval(
377
+ id: string,
378
+ response: {
379
+ /** @public */
380
+ action: "accept" | "feedback" | "decline";
381
+ /** @public */
382
+ feedback?: string;
383
+ },
384
+ ): Promise<ExtensionTestResponse>;
385
+ }
386
+
387
+ /** Disposable persistent extension test environment. @public */
388
+ export interface ExtensionIntegrationHarness {
389
+ /** Detached processes discovered or launched by extensions. @public */
390
+ processes(): TestObservation<ProcessInstance[]>;
391
+
392
+ /** @public */
393
+ request(input: ExtensionTestRequest): Promise<ExtensionTestResponse>;
394
+ /** @public */
395
+ process(id: string): ExtensionIntegrationProcess;
396
+ /** @public */
397
+ launch(id: string, input: Record<string, unknown>): Promise<ExtensionIntegrationProcess>;
398
+ /** @public */
399
+ createProcess<TParams, TState>(
400
+ definition: ExtensionProcessDefinition<TParams, TState>,
401
+ input?: Omit<ProcessFixtureOptions<TParams, TState>, "id" | "processId"> & {
402
+ /** @public */
403
+ projects?: readonly ProcessProject[];
404
+ },
405
+ ): Promise<ExtensionIntegrationProcess>;
406
+ /** @public */
407
+ restart(options?: {
408
+ /** Update extension wiring on the reopened server. @public */
409
+ extensionConfig?: Readonly<Record<string, unknown>>;
410
+ /** Apply external changes while the server is offline. @public */
411
+ whileStopped?(): void | Promise<void>;
412
+ }): Promise<void>;
413
+ /** @public */
414
+ close(): Promise<void>;
415
+ }
416
+
417
+ /** Own server, workers, and disposable persistent storage. @public */
418
+ export async function createExtensionIntegrationHarness(
419
+ options: ExtensionIntegrationHarnessOptions,
420
+ ): Promise<ExtensionIntegrationHarness> {
421
+ const catalog = await buildExtensionCatalogFromModules([
422
+ ...(options.polling === "manual"
423
+ ? [
424
+ {
425
+ manifest: { id: "test-support-manual-polling", version: "1" },
426
+ setupServer(api: import("@leitwerk-dev/process-sdk").ServerExtensionAPI) {
427
+ const deps = api.get(coreHostCapabilities.serverSetup);
428
+ if (!deps || Array.isArray(deps)) throw new Error("Missing polling host");
429
+ deps.polling = {
430
+ create(input) {
431
+ return { poll: input.pollOnce };
432
+ },
433
+ };
434
+ },
435
+ },
436
+ ]
437
+ : []),
438
+ ...options.extensions,
439
+ ]);
440
+ const persistent = createPersistentIntegrationFixture("leitwerk-extension-test-", (config) => {
441
+ config.extensions = structuredClone(options.extensionConfig ?? {});
442
+ if (options.hostDocker && config.local_worker) config.local_worker.allow_host_docker = true;
443
+ config.pi.model_profiles = (options.models ?? []).map((model) => ({
444
+ id: model.id,
445
+ provider: model.provider,
446
+ model_id: model.modelId,
447
+ thinking_level: model.thinkingLevel ?? "off",
448
+ }));
449
+ if (options.defaultModel) {
450
+ config.pi.process_title_generation.model_profile = options.defaultModel;
451
+ config.process_configs = Object.fromEntries(
452
+ [...catalog.processes.keys()].map((id) => [
453
+ id,
454
+ {
455
+ default_model_profile: options.defaultModel,
456
+ turn_configs: {},
457
+ watchers: structuredClone(options.watchers?.[id] ?? {}),
458
+ },
459
+ ]),
460
+ );
461
+ }
462
+ });
463
+ const manual = options.execution === "manual";
464
+ let closed = false;
465
+ const pending = new Map<
466
+ string,
467
+ { turnId: string; resolve(): void; reject(error: Error): void }
468
+ >();
469
+ const permits = new Set<string>();
470
+ const executing = new Set<string>();
471
+ const scripts = new Map<string, IntegrationTurnScript>();
472
+ const observations = new Map<
473
+ string,
474
+ { prompts: string[]; toolResults: { name: string; result: unknown }[] }
475
+ >();
476
+ const context = () => {
477
+ if (closed) throw new Error("Extension integration harness is closed");
478
+ return persistent.context();
479
+ };
480
+ async function open() {
481
+ const piFactory: StubPiTreeHandleFactory = new StubPiTreeHandleFactory({
482
+ recordSessionTrace: true,
483
+ toolCallScriptResolver: async (input) => {
484
+ const id = input.instanceId;
485
+ if (!id) throw new Error("Scripted prompt has no process identity");
486
+ const observation = observations.get(id) ?? { prompts: [], toolResults: [] };
487
+ observations.set(id, observation);
488
+ const prompt = input.identifiedPromptText ?? input.promptText;
489
+ observation.prompts.push(prompt);
490
+ const session = [...piFactory.sessions]
491
+ .reverse()
492
+ .find((session) => session.treeFile === input.treeFile);
493
+ const history =
494
+ session
495
+ ?.getBranch()
496
+ .map((entry) => {
497
+ if (entry.type === "custom_message") return entry.content;
498
+ if (entry.type === "message" && entry.message) return entry.message.content;
499
+ return "";
500
+ })
501
+ .filter((value) => typeof value === "string")
502
+ .join("\n\n") ?? "";
503
+ const script = manual
504
+ ? scripts.get(id)
505
+ : await options.script?.(
506
+ id,
507
+ prompt,
508
+ observe({
509
+ turnId: context().deps.processes.getById(id)?.selectedTurnId ?? "",
510
+ cwd: input.sessionCwd ?? input.workspaceRoot ?? "",
511
+ branchId: session?.sessionId ?? "",
512
+ history,
513
+ tools: input.tools.map((tool) => ({
514
+ name: tool.name,
515
+ parameters: tool.parameters,
516
+ })),
517
+ }),
518
+ );
519
+ scripts.delete(id);
520
+ if (!script || (script.tools.length === 0 && script.markdown === undefined))
521
+ throw new Error(
522
+ `Script exhausted for process '${id}' after ${observation.prompts.length} prompt(s)`,
523
+ );
524
+ return {
525
+ thinkingChunks: script.thinking ? [...script.thinking] : undefined,
526
+ textChunks: script.markdown === undefined ? undefined : [script.markdown],
527
+ calls: script.tools.map((call) => ({
528
+ toolName: call.name,
529
+ args: structuredClone(call.arguments),
530
+ })),
531
+ afterToolResult(call, result) {
532
+ observation.toolResults.push({ name: call.toolName, result: structuredClone(result) });
533
+ const next = script.afterToolResult?.(
534
+ { name: call.toolName, arguments: structuredClone(call.args) },
535
+ structuredClone(result),
536
+ );
537
+ return next ? { toolName: next.name, args: next.arguments } : undefined;
538
+ },
539
+ };
540
+ },
541
+ });
542
+ await persistent.open({
543
+ appOverrides: options.hostDocker
544
+ ? { localWorkerDockerPreflightImpl: options.hostDocker.preflight }
545
+ : undefined,
546
+ extensionCatalog: catalog,
547
+ preProvidedCapabilities: options.capabilities,
548
+ inProcessWorkers: {
549
+ piFactory,
550
+ beforeTurnBootstrap: manual
551
+ ? (id, turnId, signal) =>
552
+ new Promise<void>((resolve, reject) => {
553
+ if (signal.aborted) {
554
+ return;
555
+ }
556
+ if (permits.delete(id)) {
557
+ resolve();
558
+ return;
559
+ }
560
+ if (pending.has(id)) {
561
+ reject(new Error(`Conflicting pending worker for '${id}'`));
562
+ return;
563
+ }
564
+ const abort = () => {
565
+ pending.delete(id);
566
+ };
567
+ signal.addEventListener("abort", abort, { once: true });
568
+ pending.set(id, {
569
+ turnId,
570
+ resolve() {
571
+ signal.removeEventListener("abort", abort);
572
+ pending.delete(id);
573
+ resolve();
574
+ },
575
+ reject,
576
+ });
577
+ })
578
+ : undefined,
579
+ },
580
+ });
581
+ }
582
+ try {
583
+ await open();
584
+ } catch (error) {
585
+ await persistent.dispose();
586
+ throw error;
587
+ }
588
+ /** @public */
589
+ async function request(input: ExtensionTestRequest) {
590
+ const response = await context().app.inject({ ...input, method: input.method ?? "GET" });
591
+ return {
592
+ /** @public */
593
+ statusCode: response.statusCode,
594
+ /** @public */
595
+ body: response.body,
596
+ /** @public */
597
+ json<T = unknown>(): T {
598
+ return JSON.parse(response.body) as T;
599
+ },
600
+ };
601
+ }
602
+ async function post(url: string, payload: Record<string, unknown> = {}) {
603
+ const response = await request({ method: "POST", url, payload });
604
+ if (response.statusCode >= 400)
605
+ throw new Error(`POST ${url}: ${response.statusCode} ${response.body}`);
606
+ return response;
607
+ }
608
+ /** @public */
609
+ function processHandle(id: string): ExtensionIntegrationProcess {
610
+ const prefix = `/api/processes/${encodeURIComponent(id)}`;
611
+ /** @public */
612
+ function snapshot(): TestObservation<ExtensionIntegrationSnapshot> {
613
+ const { deps } = context();
614
+ const process = deps.processes.getById(id);
615
+ if (!process) throw new Error(`Unknown process '${id}'`);
616
+ const definition = catalog.processes.get(process.processId);
617
+ return observe({
618
+ workspaceRoot: path.join(context().config.storage.process_workspaces_dir, id),
619
+ events: deps.events.listByInstance(id),
620
+ annotations: deps.turnAnnotations.listByInstance(id),
621
+ leafOutcomes: deps.leafOutcomeSnapshots.listByInstance(id),
622
+ process,
623
+ params: definition?.paramsCodec.parse(JSON.parse(process.paramsJson ?? "null")),
624
+ state: definition?.stateCodec.parse(JSON.parse(process.stateJson ?? "null")),
625
+ projects: deps.projects.listByInstance(id),
626
+ turns: deps.turnRecords.listByInstance(id),
627
+ inputs: deps.inputs.listByInstance(id),
628
+ questions: deps.questionRequests.listByInstance(id),
629
+ approvals: deps.toolApprovalRequests.listByInstance(id),
630
+ writeReceipts: deps.externalWrites.listByInstance(id),
631
+ });
632
+ }
633
+ /** @public */
634
+ async function waitFor(
635
+ condition: (snapshot: TestObservation<ExtensionIntegrationSnapshot>) => boolean,
636
+ options: {
637
+ /** @public */
638
+ timeoutMs?: number;
639
+ /** @public */
640
+ description?: string;
641
+ } = {},
642
+ ) {
643
+ const deadline = Date.now() + (options.timeoutMs ?? 12000);
644
+ for (;;) {
645
+ const current = snapshot();
646
+ if (condition(current)) return current;
647
+ if (Date.now() >= deadline)
648
+ throw new Error(
649
+ `Timed out waiting for ${id}: ${options.description ?? "condition"}; ${JSON.stringify({
650
+ position: {
651
+ selectedTurnId: current.process.selectedTurnId,
652
+ lifecycleStatus: current.process.lifecycleStatus,
653
+ },
654
+ turns: current.turns.map((turn) => ({
655
+ id: turn.id,
656
+ turnId: turn.turnId,
657
+ status: turn.status,
658
+ error: turn.errorSummary,
659
+ })),
660
+ inputs: current.inputs.map((input) => ({
661
+ id: input.id,
662
+ consumedAt: input.consumedAt,
663
+ })),
664
+ questions: current.questions.map((question) => ({
665
+ id: question.id,
666
+ status: question.status,
667
+ })),
668
+ approvals: current.approvals.map((approval) => ({
669
+ id: approval.id,
670
+ status: approval.status,
671
+ })),
672
+ })}`,
673
+ );
674
+ await new Promise((resolve) => setTimeout(resolve, 10));
675
+ }
676
+ }
677
+ return {
678
+ /** @public */
679
+ id,
680
+ /** Establish correlated accepted records under exclusive server coordination. @public */
681
+ async seedAcceptedTurn(fixture: AcceptedTurnFixture) {
682
+ const ctx = context();
683
+ return ctx.deps.processOperations.runExclusive(id, async () => {
684
+ const process = ctx.deps.processes.getById(id);
685
+ if (!process) throw new Error(`Unknown process '${id}'`);
686
+ const turn = catalog.processes
687
+ .get(process.processId)
688
+ ?.turns.get(fixture.turnId)?.definition;
689
+ if (!turn || (turn.kind !== "llm" && turn.kind !== "automatic"))
690
+ throw new Error(`Undeclared worker turn '${fixture.turnId}'`);
691
+ if (process.currentExecution || ctx.deps.leases.getByInstance(id))
692
+ throw new Error("Cannot seed accepted execution while a live execution exists");
693
+ const running = fixture.execution.status === "running";
694
+ if (running && process.selectedTurnId !== fixture.turnId)
695
+ throw new Error("Running fixture must match the selected turn");
696
+ if (
697
+ fixture.execution.status === "succeeded" &&
698
+ !Object.hasOwn(turn.outcomes ?? {}, fixture.execution.outcome) &&
699
+ turn.turnEnd?.outcome !== fixture.execution.outcome
700
+ )
701
+ throw new Error(`Undeclared outcome '${fixture.execution.outcome}'`);
702
+ if (fixture.execution.status === "succeeded" && !fixture.execution.markdown.trim())
703
+ throw new Error("A successful accepted fixture requires non-empty result markdown");
704
+ const prepared =
705
+ turn.kind === "llm"
706
+ ? await prepareAcceptedFixtureStart(
707
+ ctx,
708
+ process,
709
+ fixture.turnId,
710
+ catalog.piContributions,
711
+ )
712
+ : null;
713
+ return ctx.deps.transaction((repos) => {
714
+ const turnId = `trn_${randomUUID()}`;
715
+ const timestamp = new Date().toISOString();
716
+ const input = {
717
+ id: turnId,
718
+ instanceId: id,
719
+ turnId: fixture.turnId,
720
+ status: fixture.execution.status,
721
+ attemptNumber:
722
+ Math.max(
723
+ 0,
724
+ ...repos.turnRecords
725
+ .listByInstance(id)
726
+ .filter((record) => record.turnId === fixture.turnId)
727
+ .map((record) => record.attemptNumber),
728
+ ) + 1,
729
+ startedAt: timestamp,
730
+ endedAt: running ? null : timestamp,
731
+ turnResultMarkdown:
732
+ fixture.execution.status === "succeeded" ? fixture.execution.markdown : null,
733
+ };
734
+ if (turn.kind === "llm") {
735
+ if (!prepared) throw new Error("Missing fixture preparation");
736
+ const bundleDir = path.join(
737
+ ctx.config.storage.process_workspaces_dir,
738
+ id,
739
+ ".leitwerk",
740
+ "pi-resource-bundles",
741
+ );
742
+ mkdirSync(path.join(bundleDir, "starts"), { recursive: true, mode: 0o700 });
743
+ writeFileSync(
744
+ path.join(bundleDir, `${prepared.bundle.digest}.tar`),
745
+ prepared.bundle.bytes,
746
+ { mode: 0o600 },
747
+ );
748
+ writeFileSync(
749
+ path.join(bundleDir, "starts", `tsr_${turnId}.json`),
750
+ JSON.stringify({
751
+ startRecordId: `tsr_${turnId}`,
752
+ digest: prepared.bundle.digest,
753
+ persistedAt: timestamp,
754
+ }),
755
+ { mode: 0o600 },
756
+ );
757
+
758
+ createAcceptedLlmTurn(
759
+ {
760
+ ...ctx,
761
+ deps: {
762
+ ...ctx.deps,
763
+ processes: repos.processes,
764
+ turnRecords: repos.turnRecords,
765
+ turnStarts: repos.turnStarts,
766
+ leases: repos.leases,
767
+ },
768
+ },
769
+ { ...input, turnType: "llm", modelProfileId: prepared.start.model.profileId },
770
+ { current: running, preparedStart: prepared?.start },
771
+ );
772
+ } else {
773
+ const lease = repos.leases.create({
774
+ instanceId: id,
775
+ workerId: `wkr_${randomUUID()}`,
776
+ state: running ? "busy" : "exited",
777
+ });
778
+ const start = repos.turnStarts.create({
779
+ instanceId: id,
780
+ turnId: fixture.turnId,
781
+ turnType: "automatic",
782
+ proposedTurnRecordId: turnId,
783
+ startKind: "selected_turn",
784
+ recoveryTurnRecordId: null,
785
+ continuation: null,
786
+ state: {
787
+ kind: "accepted",
788
+ start: { kind: "automatic" },
789
+ turnRecordId: turnId,
790
+ acceptedWorkerLeaseId: lease.id,
791
+ },
792
+ });
793
+ repos.turnRecords.create({
794
+ ...input,
795
+ turnType: "automatic",
796
+ turnStartRecordId: start.id,
797
+ acceptedWorkerLeaseId: lease.id,
798
+ });
799
+ if (running)
800
+ repos.processes.update(id, {
801
+ currentExecution: { kind: "worker_start", id: start.id },
802
+ });
803
+ else repos.leases.update(lease.id, { exitedAt: timestamp });
804
+ }
805
+ if (fixture.execution.status === "succeeded")
806
+ repos.turnAnnotations.create({
807
+ instanceId: id,
808
+ annotationType: "turn_milestone",
809
+ annotationKey: `turn_milestone:${turnId}`,
810
+ references: [{ kind: "turn_record", turnRecordId: turnId, role: "subject" }],
811
+ payload: {
812
+ turnId: fixture.turnId,
813
+ turnType: turn.kind,
814
+ pathType: "primary",
815
+ outcome: fixture.execution.outcome,
816
+ },
817
+ });
818
+ if (running) repos.processes.update(id, { lifecycleStatus: "active" });
819
+ return observe({
820
+ /** @public */
821
+ id: turnId,
822
+ /** @public */
823
+ instanceId: id,
824
+ /** @public */
825
+ turnId: fixture.turnId,
826
+ /** @public */
827
+ artifact: running ? null : { kind: "turn_result" as const, turnRecordId: turnId },
828
+ });
829
+ });
830
+ });
831
+ },
832
+ /** Read detached durable business and execution observations. @public */
833
+ snapshot,
834
+ /** Wait with a bounded deadline and final observations on failure. @public */
835
+ waitFor,
836
+ /** Execute one selected worker turn; resolves after durable completion or failure. @public */
837
+ async runTurn(script: IntegrationTurnScript = { tools: [] }) {
838
+ if (!manual) throw new Error("runTurn requires manual execution mode");
839
+ if (executing.has(id)) throw new Error(`A turn is already running for '${id}'`);
840
+ const before = snapshot();
841
+ const selected = before.process.selectedTurnId;
842
+ const turn = selected
843
+ ? catalog.processes.get(before.process.processId)?.turns.get(selected)?.definition
844
+ : undefined;
845
+ if (
846
+ !selected ||
847
+ !turn ||
848
+ (turn.kind !== "llm" && turn.kind !== "automatic") ||
849
+ before.process.lifecycleStatus !== "active"
850
+ )
851
+ throw new Error(`Process '${id}' has no active worker turn: ${JSON.stringify(before)}`);
852
+ executing.add(id);
853
+ const previous = new Set(before.turns.map((turn) => turn.id));
854
+ observations.set(id, { prompts: [], toolResults: [] });
855
+ scripts.set(id, script);
856
+ try {
857
+ const gate = pending.get(id);
858
+ if (gate) {
859
+ if (gate.turnId !== selected)
860
+ throw new Error("Pending turn does not match selected turn");
861
+ gate.resolve();
862
+ } else permits.add(id);
863
+ const after = await waitFor(
864
+ (current) =>
865
+ current.turns.some((turn) => !previous.has(turn.id) && turn.status !== "running") ||
866
+ current.process.lifecycleStatus === "error",
867
+ { description: `durable outcome of ${selected}` },
868
+ );
869
+ const record = after.turns.find((turn) => !previous.has(turn.id));
870
+ const milestone = record
871
+ ? context().deps.turnAnnotations.findByKey(id, `turn_milestone:${record.id}`)
872
+ : null;
873
+ return observe({
874
+ /** @public */
875
+ turn: record ?? null,
876
+ /** @public */
877
+ outcome:
878
+ typeof milestone?.payload.outcome === "string" ? milestone.payload.outcome : null,
879
+ /** @public */
880
+ failure:
881
+ record?.errorSummary ??
882
+ (after.process.lifecycleStatus === "error"
883
+ ? "Worker start failed before acceptance"
884
+ : null),
885
+ /** @public */
886
+ prompts: observations.get(id)?.prompts ?? [],
887
+ /** @public */
888
+ toolResults: observations.get(id)?.toolResults ?? [],
889
+ /** @public */
890
+ result:
891
+ record?.status === "succeeded" && record.turnResultMarkdown
892
+ ? { kind: "turn_result" as const, turnRecordId: record.id }
893
+ : null,
894
+ });
895
+ } finally {
896
+ executing.delete(id);
897
+ scripts.delete(id);
898
+ permits.delete(id);
899
+ }
900
+ },
901
+ /** Execute an application action. @public */
902
+ action: (actionId: string, input: Record<string, unknown> = {}) =>
903
+ post(`${prefix}/actions/${encodeURIComponent(actionId)}`, { input }),
904
+ /** Retry the failed execution through the application command. @public */
905
+ retry: () => post(`${prefix}/retry`),
906
+ /** Queue an instruction using the application command and normal delivery. @public */
907
+ async supplyInput(input: IntegrationProcessInput) {
908
+ const result = await context().deps.processEngine.queueInputs(id, [
909
+ {
910
+ source: "app_steer",
911
+ kind: "instruction",
912
+ bodyMarkdown: input.bodyMarkdown,
913
+ ...(input.product ? { target: { productName: input.product } } : {}),
914
+ },
915
+ ]);
916
+ if (!result.ok) throw new Error(`Input rejected: ${result.message}`);
917
+ return snapshot();
918
+ },
919
+ /** Answer an open question request. @public */
920
+ answerQuestions: (
921
+ requestId: string,
922
+ answers: readonly {
923
+ /** @public */
924
+ selectedOptionIds: readonly string[];
925
+ /** @public */
926
+ freeText: string;
927
+ /** @public */
928
+ comment: string;
929
+ }[],
930
+ ) =>
931
+ post(`${prefix}/question-requests/${encodeURIComponent(requestId)}/answers`, {
932
+ draft: answers,
933
+ }),
934
+ /** Resolve an open tool approval. @public */
935
+ respondToApproval: (
936
+ requestId: string,
937
+ response: {
938
+ /** @public */
939
+ action: "accept" | "feedback" | "decline";
940
+ /** @public */
941
+ feedback?: string;
942
+ },
943
+ ) => post(`${prefix}/tool-approval-requests/${encodeURIComponent(requestId)}`, response),
944
+ };
945
+ }
946
+ return {
947
+ /** Observe discovered processes. @public */
948
+ processes: () => observe(context().deps.processes.listAll()),
949
+ /** Send an HTTP-shaped request, retaining error status and body. @public */
950
+ request,
951
+ /** Get a handle that remains valid across restart. @public */
952
+ process: processHandle,
953
+ /** Admit work through a registered UI launcher. @public */
954
+ async launch(id: string, input: Record<string, unknown>) {
955
+ const response = await postImmediateLaunch(context().config.server.base_url, id, {
956
+ launcherInput: input,
957
+ });
958
+ const body = (await response.json()) as { process?: { id: string } };
959
+ if (!response.ok || !body.process)
960
+ throw new Error(`Launch '${id}' failed: ${JSON.stringify(body)}`);
961
+ return processHandle(body.process.id);
962
+ },
963
+ /** Create validated business data and start an active position through the engine. @public */
964
+ async createProcess<TParams, TState>(
965
+ definition: ExtensionProcessDefinition<TParams, TState>,
966
+ input: Omit<ProcessFixtureOptions<TParams, TState>, "id" | "processId"> & {
967
+ /** @public */
968
+ projects?: readonly ProcessProject[];
969
+ } = {},
970
+ ) {
971
+ if (catalog.processes.get(definition.id) !== definition)
972
+ throw new Error(`Process '${definition.id}' must be registered by an extension`);
973
+ const fixture = createProcessFixture(input, definition);
974
+ const { deps } = context();
975
+ const process = deps.transaction((repos) => {
976
+ const process = repos.processes.create({
977
+ processId: definition.id,
978
+ title: fixture.title,
979
+ externalId: fixture.externalId,
980
+ externalUrl: fixture.externalUrl,
981
+ metadata: fixture.metadata,
982
+ paramsJson: fixture.paramsJson,
983
+ stateJson: fixture.stateJson,
984
+ selectedTurnId: fixture.selectedTurnId,
985
+ lifecycleStatus:
986
+ fixture.lifecycleStatus === "active" ? "waiting" : fixture.lifecycleStatus,
987
+ });
988
+ if (fixture.planRevision !== 0)
989
+ repos.processes.update(process.id, { planRevision: fixture.planRevision });
990
+ for (const project of input.projects ?? [])
991
+ repos.projects.create({
992
+ instanceId: process.id,
993
+ key: project.key,
994
+ repoLocator: project.repoLocator,
995
+ baseBranch: project.baseBranch,
996
+ workBranch: project.workBranch,
997
+ metadata: project.metadata,
998
+ externalId: project.externalId,
999
+ externalUrl: project.externalUrl,
1000
+ pipelineStatus: project.pipelineStatus,
1001
+ });
1002
+ return process;
1003
+ });
1004
+ if (fixture.lifecycleStatus === "active" && fixture.selectedTurnId) {
1005
+ const result = await deps.processEngine.startProcess(process.id, fixture.selectedTurnId);
1006
+ if (!result.ok) throw new Error(`Process start failed: ${result.message}`);
1007
+ }
1008
+ return processHandle(process.id);
1009
+ },
1010
+ /** Reopen the same file-backed storage and retain existing handles. @public */
1011
+ async restart(restartOptions = {}) {
1012
+ if (executing.size) throw new Error("Cannot restart during runTurn");
1013
+ const { deps } = context();
1014
+ const paused = manual
1015
+ ? deps.processes.listAll().flatMap((process) => {
1016
+ if (
1017
+ process.lifecycleStatus !== "active" ||
1018
+ process.currentExecution?.kind !== "worker_start"
1019
+ )
1020
+ return [];
1021
+ const start = deps.turnStarts.getById(process.currentExecution.id);
1022
+ return start?.state.kind === "starting"
1023
+ ? [{ instanceId: process.id, startId: start.id }]
1024
+ : [];
1025
+ })
1026
+ : [];
1027
+ await persistent.close();
1028
+ if (restartOptions.extensionConfig)
1029
+ options.extensionConfig = structuredClone(restartOptions.extensionConfig);
1030
+ await restartOptions.whileStopped?.();
1031
+ pending.clear();
1032
+ permits.clear();
1033
+ scripts.clear();
1034
+ await open();
1035
+ for (const pausedStart of paused) {
1036
+ if (context().deps.processes.getById(pausedStart.instanceId)?.lifecycleStatus !== "error")
1037
+ continue;
1038
+ const result = await context().deps.processEngine.retryStartup(
1039
+ pausedStart.instanceId,
1040
+ pausedStart.startId,
1041
+ );
1042
+ if (!result.ok)
1043
+ throw new Error(`Cannot restore paused turn after restart: ${result.message}`);
1044
+ }
1045
+ },
1046
+ /** Release all resources and remove harness-owned files. @public */
1047
+ async close() {
1048
+ if (closed) return;
1049
+ closed = true;
1050
+ try {
1051
+ await persistent.dispose();
1052
+ } finally {
1053
+ pending.clear();
1054
+ permits.clear();
1055
+ scripts.clear();
1056
+ }
1057
+ },
1058
+ };
1059
+ }