@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
@@ -1,3 +1,4 @@
1
+ export { type AcceptedTurnFixture, type AcceptedTurnReference, createExtensionIntegrationHarness, type ExtensionIntegrationHarness, type ExtensionIntegrationHarnessOptions, type ExtensionIntegrationProcess, type ExtensionIntegrationSnapshot, type ExtensionTestRequest, type ExtensionTestResponse, type IntegrationAnnotationObservation, type IntegrationApprovalObservation, type IntegrationEventObservation, type IntegrationInputObservation, type IntegrationLeafObservation, type IntegrationProcessInput, type IntegrationPromptObservation, type IntegrationToolCall, type IntegrationTurnResult, type IntegrationTurnScript, } from "./extension-integration-harness.js";
1
2
  export { createIntegrationHarness, createPersistentIntegrationFixture, type IntegrationHarness, } from "./integration-harness.js";
2
3
  export { waitForValue } from "./polling.js";
3
4
  export { createProcessDriver } from "./process-driver.js";
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../src/integration.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,wBAAwB,EACxB,kCAAkC,EAClC,KAAK,kBAAkB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,oCAAoC,CAAC"}
1
+ {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../src/integration.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,iCAAiC,EACjC,KAAK,2BAA2B,EAChC,KAAK,kCAAkC,EACvC,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACnC,KAAK,2BAA2B,EAChC,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,EAC5B,KAAK,4BAA4B,EACjC,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,GAC1B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACN,wBAAwB,EACxB,kCAAkC,EAClC,KAAK,kBAAkB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,oCAAoC,CAAC"}
@@ -1,10 +1,31 @@
1
+ import {
2
+ postImmediateLaunch
3
+ } from "./chunk-P2FF4AP7.js";
4
+ import {
5
+ observe
6
+ } from "./chunk-KJVNI2UP.js";
7
+ import {
8
+ createProcessFixture
9
+ } from "./chunk-RY6Y6V5E.js";
1
10
  import {
2
11
  createTestServerSetupCapability
3
12
  } from "./chunk-5BZSJ4OO.js";
4
13
  import {
5
14
  createInProcessWorkerSpawn
6
- } from "./chunk-2PCDTYVH.js";
7
- import "./chunk-ECAWLVYB.js";
15
+ } from "./chunk-OE4NHDVS.js";
16
+ import {
17
+ StubPiTreeHandleFactory
18
+ } from "./chunk-E4Y7XND5.js";
19
+
20
+ // src/extension-integration-harness.ts
21
+ import { randomUUID } from "crypto";
22
+ import { mkdirSync, writeFileSync } from "fs";
23
+ import path2 from "path";
24
+ import { buildExtensionCatalogFromModules } from "@leitwerk-dev/extension-runtime/testing";
25
+ import {
26
+ coreHostCapabilities
27
+ } from "@leitwerk-dev/process-sdk";
28
+ import { createAcceptedLlmTurn, prepareAcceptedFixtureStart } from "@leitwerk-dev/server/testing";
8
29
 
9
30
  // src/integration-harness.ts
10
31
  import { mkdtempSync, rmSync } from "fs";
@@ -111,6 +132,546 @@ async function createIntegrationHarness(opts) {
111
132
  };
112
133
  }
113
134
 
135
+ // src/extension-integration-harness.ts
136
+ async function createExtensionIntegrationHarness(options) {
137
+ const catalog = await buildExtensionCatalogFromModules([
138
+ ...options.polling === "manual" ? [
139
+ {
140
+ manifest: { id: "test-support-manual-polling", version: "1" },
141
+ setupServer(api) {
142
+ const deps = api.get(coreHostCapabilities.serverSetup);
143
+ if (!deps || Array.isArray(deps)) throw new Error("Missing polling host");
144
+ deps.polling = {
145
+ create(input) {
146
+ return { poll: input.pollOnce };
147
+ }
148
+ };
149
+ }
150
+ }
151
+ ] : [],
152
+ ...options.extensions
153
+ ]);
154
+ const persistent = createPersistentIntegrationFixture("leitwerk-extension-test-", (config) => {
155
+ config.extensions = structuredClone(options.extensionConfig ?? {});
156
+ if (options.hostDocker && config.local_worker) config.local_worker.allow_host_docker = true;
157
+ config.pi.model_profiles = (options.models ?? []).map((model) => ({
158
+ id: model.id,
159
+ provider: model.provider,
160
+ model_id: model.modelId,
161
+ thinking_level: model.thinkingLevel ?? "off"
162
+ }));
163
+ if (options.defaultModel) {
164
+ config.pi.process_title_generation.model_profile = options.defaultModel;
165
+ config.process_configs = Object.fromEntries(
166
+ [...catalog.processes.keys()].map((id) => [
167
+ id,
168
+ {
169
+ default_model_profile: options.defaultModel,
170
+ turn_configs: {},
171
+ watchers: structuredClone(options.watchers?.[id] ?? {})
172
+ }
173
+ ])
174
+ );
175
+ }
176
+ });
177
+ const manual = options.execution === "manual";
178
+ let closed = false;
179
+ const pending = /* @__PURE__ */ new Map();
180
+ const permits = /* @__PURE__ */ new Set();
181
+ const executing = /* @__PURE__ */ new Set();
182
+ const scripts = /* @__PURE__ */ new Map();
183
+ const observations = /* @__PURE__ */ new Map();
184
+ const context = () => {
185
+ if (closed) throw new Error("Extension integration harness is closed");
186
+ return persistent.context();
187
+ };
188
+ async function open() {
189
+ const piFactory = new StubPiTreeHandleFactory({
190
+ recordSessionTrace: true,
191
+ toolCallScriptResolver: async (input) => {
192
+ const id = input.instanceId;
193
+ if (!id) throw new Error("Scripted prompt has no process identity");
194
+ const observation = observations.get(id) ?? { prompts: [], toolResults: [] };
195
+ observations.set(id, observation);
196
+ const prompt = input.identifiedPromptText ?? input.promptText;
197
+ observation.prompts.push(prompt);
198
+ const session = [...piFactory.sessions].reverse().find((session2) => session2.treeFile === input.treeFile);
199
+ const history = session?.getBranch().map((entry) => {
200
+ if (entry.type === "custom_message") return entry.content;
201
+ if (entry.type === "message" && entry.message) return entry.message.content;
202
+ return "";
203
+ }).filter((value) => typeof value === "string").join("\n\n") ?? "";
204
+ const script = manual ? scripts.get(id) : await options.script?.(
205
+ id,
206
+ prompt,
207
+ observe({
208
+ turnId: context().deps.processes.getById(id)?.selectedTurnId ?? "",
209
+ cwd: input.sessionCwd ?? input.workspaceRoot ?? "",
210
+ branchId: session?.sessionId ?? "",
211
+ history,
212
+ tools: input.tools.map((tool) => ({
213
+ name: tool.name,
214
+ parameters: tool.parameters
215
+ }))
216
+ })
217
+ );
218
+ scripts.delete(id);
219
+ if (!script || script.tools.length === 0 && script.markdown === void 0)
220
+ throw new Error(
221
+ `Script exhausted for process '${id}' after ${observation.prompts.length} prompt(s)`
222
+ );
223
+ return {
224
+ thinkingChunks: script.thinking ? [...script.thinking] : void 0,
225
+ textChunks: script.markdown === void 0 ? void 0 : [script.markdown],
226
+ calls: script.tools.map((call) => ({
227
+ toolName: call.name,
228
+ args: structuredClone(call.arguments)
229
+ })),
230
+ afterToolResult(call, result) {
231
+ observation.toolResults.push({ name: call.toolName, result: structuredClone(result) });
232
+ const next = script.afterToolResult?.(
233
+ { name: call.toolName, arguments: structuredClone(call.args) },
234
+ structuredClone(result)
235
+ );
236
+ return next ? { toolName: next.name, args: next.arguments } : void 0;
237
+ }
238
+ };
239
+ }
240
+ });
241
+ await persistent.open({
242
+ appOverrides: options.hostDocker ? { localWorkerDockerPreflightImpl: options.hostDocker.preflight } : void 0,
243
+ extensionCatalog: catalog,
244
+ preProvidedCapabilities: options.capabilities,
245
+ inProcessWorkers: {
246
+ piFactory,
247
+ beforeTurnBootstrap: manual ? (id, turnId, signal) => new Promise((resolve, reject) => {
248
+ if (signal.aborted) {
249
+ return;
250
+ }
251
+ if (permits.delete(id)) {
252
+ resolve();
253
+ return;
254
+ }
255
+ if (pending.has(id)) {
256
+ reject(new Error(`Conflicting pending worker for '${id}'`));
257
+ return;
258
+ }
259
+ const abort = () => {
260
+ pending.delete(id);
261
+ };
262
+ signal.addEventListener("abort", abort, { once: true });
263
+ pending.set(id, {
264
+ turnId,
265
+ resolve() {
266
+ signal.removeEventListener("abort", abort);
267
+ pending.delete(id);
268
+ resolve();
269
+ },
270
+ reject
271
+ });
272
+ }) : void 0
273
+ }
274
+ });
275
+ }
276
+ try {
277
+ await open();
278
+ } catch (error) {
279
+ await persistent.dispose();
280
+ throw error;
281
+ }
282
+ async function request(input) {
283
+ const response = await context().app.inject({ ...input, method: input.method ?? "GET" });
284
+ return {
285
+ /** @public */
286
+ statusCode: response.statusCode,
287
+ /** @public */
288
+ body: response.body,
289
+ /** @public */
290
+ json() {
291
+ return JSON.parse(response.body);
292
+ }
293
+ };
294
+ }
295
+ async function post(url, payload = {}) {
296
+ const response = await request({ method: "POST", url, payload });
297
+ if (response.statusCode >= 400)
298
+ throw new Error(`POST ${url}: ${response.statusCode} ${response.body}`);
299
+ return response;
300
+ }
301
+ function processHandle(id) {
302
+ const prefix = `/api/processes/${encodeURIComponent(id)}`;
303
+ function snapshot() {
304
+ const { deps } = context();
305
+ const process = deps.processes.getById(id);
306
+ if (!process) throw new Error(`Unknown process '${id}'`);
307
+ const definition = catalog.processes.get(process.processId);
308
+ return observe({
309
+ workspaceRoot: path2.join(context().config.storage.process_workspaces_dir, id),
310
+ events: deps.events.listByInstance(id),
311
+ annotations: deps.turnAnnotations.listByInstance(id),
312
+ leafOutcomes: deps.leafOutcomeSnapshots.listByInstance(id),
313
+ process,
314
+ params: definition?.paramsCodec.parse(JSON.parse(process.paramsJson ?? "null")),
315
+ state: definition?.stateCodec.parse(JSON.parse(process.stateJson ?? "null")),
316
+ projects: deps.projects.listByInstance(id),
317
+ turns: deps.turnRecords.listByInstance(id),
318
+ inputs: deps.inputs.listByInstance(id),
319
+ questions: deps.questionRequests.listByInstance(id),
320
+ approvals: deps.toolApprovalRequests.listByInstance(id),
321
+ writeReceipts: deps.externalWrites.listByInstance(id)
322
+ });
323
+ }
324
+ async function waitFor(condition, options2 = {}) {
325
+ const deadline = Date.now() + (options2.timeoutMs ?? 12e3);
326
+ for (; ; ) {
327
+ const current = snapshot();
328
+ if (condition(current)) return current;
329
+ if (Date.now() >= deadline)
330
+ throw new Error(
331
+ `Timed out waiting for ${id}: ${options2.description ?? "condition"}; ${JSON.stringify({
332
+ position: {
333
+ selectedTurnId: current.process.selectedTurnId,
334
+ lifecycleStatus: current.process.lifecycleStatus
335
+ },
336
+ turns: current.turns.map((turn) => ({
337
+ id: turn.id,
338
+ turnId: turn.turnId,
339
+ status: turn.status,
340
+ error: turn.errorSummary
341
+ })),
342
+ inputs: current.inputs.map((input) => ({
343
+ id: input.id,
344
+ consumedAt: input.consumedAt
345
+ })),
346
+ questions: current.questions.map((question) => ({
347
+ id: question.id,
348
+ status: question.status
349
+ })),
350
+ approvals: current.approvals.map((approval) => ({
351
+ id: approval.id,
352
+ status: approval.status
353
+ }))
354
+ })}`
355
+ );
356
+ await new Promise((resolve) => setTimeout(resolve, 10));
357
+ }
358
+ }
359
+ return {
360
+ /** @public */
361
+ id,
362
+ /** Establish correlated accepted records under exclusive server coordination. @public */
363
+ async seedAcceptedTurn(fixture) {
364
+ const ctx = context();
365
+ return ctx.deps.processOperations.runExclusive(id, async () => {
366
+ const process = ctx.deps.processes.getById(id);
367
+ if (!process) throw new Error(`Unknown process '${id}'`);
368
+ const turn = catalog.processes.get(process.processId)?.turns.get(fixture.turnId)?.definition;
369
+ if (!turn || turn.kind !== "llm" && turn.kind !== "automatic")
370
+ throw new Error(`Undeclared worker turn '${fixture.turnId}'`);
371
+ if (process.currentExecution || ctx.deps.leases.getByInstance(id))
372
+ throw new Error("Cannot seed accepted execution while a live execution exists");
373
+ const running = fixture.execution.status === "running";
374
+ if (running && process.selectedTurnId !== fixture.turnId)
375
+ throw new Error("Running fixture must match the selected turn");
376
+ if (fixture.execution.status === "succeeded" && !Object.hasOwn(turn.outcomes ?? {}, fixture.execution.outcome) && turn.turnEnd?.outcome !== fixture.execution.outcome)
377
+ throw new Error(`Undeclared outcome '${fixture.execution.outcome}'`);
378
+ if (fixture.execution.status === "succeeded" && !fixture.execution.markdown.trim())
379
+ throw new Error("A successful accepted fixture requires non-empty result markdown");
380
+ const prepared = turn.kind === "llm" ? await prepareAcceptedFixtureStart(
381
+ ctx,
382
+ process,
383
+ fixture.turnId,
384
+ catalog.piContributions
385
+ ) : null;
386
+ return ctx.deps.transaction((repos) => {
387
+ const turnId = `trn_${randomUUID()}`;
388
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
389
+ const input = {
390
+ id: turnId,
391
+ instanceId: id,
392
+ turnId: fixture.turnId,
393
+ status: fixture.execution.status,
394
+ attemptNumber: Math.max(
395
+ 0,
396
+ ...repos.turnRecords.listByInstance(id).filter((record) => record.turnId === fixture.turnId).map((record) => record.attemptNumber)
397
+ ) + 1,
398
+ startedAt: timestamp,
399
+ endedAt: running ? null : timestamp,
400
+ turnResultMarkdown: fixture.execution.status === "succeeded" ? fixture.execution.markdown : null
401
+ };
402
+ if (turn.kind === "llm") {
403
+ if (!prepared) throw new Error("Missing fixture preparation");
404
+ const bundleDir = path2.join(
405
+ ctx.config.storage.process_workspaces_dir,
406
+ id,
407
+ ".leitwerk",
408
+ "pi-resource-bundles"
409
+ );
410
+ mkdirSync(path2.join(bundleDir, "starts"), { recursive: true, mode: 448 });
411
+ writeFileSync(
412
+ path2.join(bundleDir, `${prepared.bundle.digest}.tar`),
413
+ prepared.bundle.bytes,
414
+ { mode: 384 }
415
+ );
416
+ writeFileSync(
417
+ path2.join(bundleDir, "starts", `tsr_${turnId}.json`),
418
+ JSON.stringify({
419
+ startRecordId: `tsr_${turnId}`,
420
+ digest: prepared.bundle.digest,
421
+ persistedAt: timestamp
422
+ }),
423
+ { mode: 384 }
424
+ );
425
+ createAcceptedLlmTurn(
426
+ {
427
+ ...ctx,
428
+ deps: {
429
+ ...ctx.deps,
430
+ processes: repos.processes,
431
+ turnRecords: repos.turnRecords,
432
+ turnStarts: repos.turnStarts,
433
+ leases: repos.leases
434
+ }
435
+ },
436
+ { ...input, turnType: "llm", modelProfileId: prepared.start.model.profileId },
437
+ { current: running, preparedStart: prepared?.start }
438
+ );
439
+ } else {
440
+ const lease = repos.leases.create({
441
+ instanceId: id,
442
+ workerId: `wkr_${randomUUID()}`,
443
+ state: running ? "busy" : "exited"
444
+ });
445
+ const start = repos.turnStarts.create({
446
+ instanceId: id,
447
+ turnId: fixture.turnId,
448
+ turnType: "automatic",
449
+ proposedTurnRecordId: turnId,
450
+ startKind: "selected_turn",
451
+ recoveryTurnRecordId: null,
452
+ continuation: null,
453
+ state: {
454
+ kind: "accepted",
455
+ start: { kind: "automatic" },
456
+ turnRecordId: turnId,
457
+ acceptedWorkerLeaseId: lease.id
458
+ }
459
+ });
460
+ repos.turnRecords.create({
461
+ ...input,
462
+ turnType: "automatic",
463
+ turnStartRecordId: start.id,
464
+ acceptedWorkerLeaseId: lease.id
465
+ });
466
+ if (running)
467
+ repos.processes.update(id, {
468
+ currentExecution: { kind: "worker_start", id: start.id }
469
+ });
470
+ else repos.leases.update(lease.id, { exitedAt: timestamp });
471
+ }
472
+ if (fixture.execution.status === "succeeded")
473
+ repos.turnAnnotations.create({
474
+ instanceId: id,
475
+ annotationType: "turn_milestone",
476
+ annotationKey: `turn_milestone:${turnId}`,
477
+ references: [{ kind: "turn_record", turnRecordId: turnId, role: "subject" }],
478
+ payload: {
479
+ turnId: fixture.turnId,
480
+ turnType: turn.kind,
481
+ pathType: "primary",
482
+ outcome: fixture.execution.outcome
483
+ }
484
+ });
485
+ if (running) repos.processes.update(id, { lifecycleStatus: "active" });
486
+ return observe({
487
+ /** @public */
488
+ id: turnId,
489
+ /** @public */
490
+ instanceId: id,
491
+ /** @public */
492
+ turnId: fixture.turnId,
493
+ /** @public */
494
+ artifact: running ? null : { kind: "turn_result", turnRecordId: turnId }
495
+ });
496
+ });
497
+ });
498
+ },
499
+ /** Read detached durable business and execution observations. @public */
500
+ snapshot,
501
+ /** Wait with a bounded deadline and final observations on failure. @public */
502
+ waitFor,
503
+ /** Execute one selected worker turn; resolves after durable completion or failure. @public */
504
+ async runTurn(script = { tools: [] }) {
505
+ if (!manual) throw new Error("runTurn requires manual execution mode");
506
+ if (executing.has(id)) throw new Error(`A turn is already running for '${id}'`);
507
+ const before = snapshot();
508
+ const selected = before.process.selectedTurnId;
509
+ const turn = selected ? catalog.processes.get(before.process.processId)?.turns.get(selected)?.definition : void 0;
510
+ if (!selected || !turn || turn.kind !== "llm" && turn.kind !== "automatic" || before.process.lifecycleStatus !== "active")
511
+ throw new Error(`Process '${id}' has no active worker turn: ${JSON.stringify(before)}`);
512
+ executing.add(id);
513
+ const previous = new Set(before.turns.map((turn2) => turn2.id));
514
+ observations.set(id, { prompts: [], toolResults: [] });
515
+ scripts.set(id, script);
516
+ try {
517
+ const gate = pending.get(id);
518
+ if (gate) {
519
+ if (gate.turnId !== selected)
520
+ throw new Error("Pending turn does not match selected turn");
521
+ gate.resolve();
522
+ } else permits.add(id);
523
+ const after = await waitFor(
524
+ (current) => current.turns.some((turn2) => !previous.has(turn2.id) && turn2.status !== "running") || current.process.lifecycleStatus === "error",
525
+ { description: `durable outcome of ${selected}` }
526
+ );
527
+ const record = after.turns.find((turn2) => !previous.has(turn2.id));
528
+ const milestone = record ? context().deps.turnAnnotations.findByKey(id, `turn_milestone:${record.id}`) : null;
529
+ return observe({
530
+ /** @public */
531
+ turn: record ?? null,
532
+ /** @public */
533
+ outcome: typeof milestone?.payload.outcome === "string" ? milestone.payload.outcome : null,
534
+ /** @public */
535
+ failure: record?.errorSummary ?? (after.process.lifecycleStatus === "error" ? "Worker start failed before acceptance" : null),
536
+ /** @public */
537
+ prompts: observations.get(id)?.prompts ?? [],
538
+ /** @public */
539
+ toolResults: observations.get(id)?.toolResults ?? [],
540
+ /** @public */
541
+ result: record?.status === "succeeded" && record.turnResultMarkdown ? { kind: "turn_result", turnRecordId: record.id } : null
542
+ });
543
+ } finally {
544
+ executing.delete(id);
545
+ scripts.delete(id);
546
+ permits.delete(id);
547
+ }
548
+ },
549
+ /** Execute an application action. @public */
550
+ action: (actionId, input = {}) => post(`${prefix}/actions/${encodeURIComponent(actionId)}`, { input }),
551
+ /** Retry the failed execution through the application command. @public */
552
+ retry: () => post(`${prefix}/retry`),
553
+ /** Queue an instruction using the application command and normal delivery. @public */
554
+ async supplyInput(input) {
555
+ const result = await context().deps.processEngine.queueInputs(id, [
556
+ {
557
+ source: "app_steer",
558
+ kind: "instruction",
559
+ bodyMarkdown: input.bodyMarkdown,
560
+ ...input.product ? { target: { productName: input.product } } : {}
561
+ }
562
+ ]);
563
+ if (!result.ok) throw new Error(`Input rejected: ${result.message}`);
564
+ return snapshot();
565
+ },
566
+ /** Answer an open question request. @public */
567
+ answerQuestions: (requestId, answers) => post(`${prefix}/question-requests/${encodeURIComponent(requestId)}/answers`, {
568
+ draft: answers
569
+ }),
570
+ /** Resolve an open tool approval. @public */
571
+ respondToApproval: (requestId, response) => post(`${prefix}/tool-approval-requests/${encodeURIComponent(requestId)}`, response)
572
+ };
573
+ }
574
+ return {
575
+ /** Observe discovered processes. @public */
576
+ processes: () => observe(context().deps.processes.listAll()),
577
+ /** Send an HTTP-shaped request, retaining error status and body. @public */
578
+ request,
579
+ /** Get a handle that remains valid across restart. @public */
580
+ process: processHandle,
581
+ /** Admit work through a registered UI launcher. @public */
582
+ async launch(id, input) {
583
+ const response = await postImmediateLaunch(context().config.server.base_url, id, {
584
+ launcherInput: input
585
+ });
586
+ const body = await response.json();
587
+ if (!response.ok || !body.process)
588
+ throw new Error(`Launch '${id}' failed: ${JSON.stringify(body)}`);
589
+ return processHandle(body.process.id);
590
+ },
591
+ /** Create validated business data and start an active position through the engine. @public */
592
+ async createProcess(definition, input = {}) {
593
+ if (catalog.processes.get(definition.id) !== definition)
594
+ throw new Error(`Process '${definition.id}' must be registered by an extension`);
595
+ const fixture = createProcessFixture(input, definition);
596
+ const { deps } = context();
597
+ const process = deps.transaction((repos) => {
598
+ const process2 = repos.processes.create({
599
+ processId: definition.id,
600
+ title: fixture.title,
601
+ externalId: fixture.externalId,
602
+ externalUrl: fixture.externalUrl,
603
+ metadata: fixture.metadata,
604
+ paramsJson: fixture.paramsJson,
605
+ stateJson: fixture.stateJson,
606
+ selectedTurnId: fixture.selectedTurnId,
607
+ lifecycleStatus: fixture.lifecycleStatus === "active" ? "waiting" : fixture.lifecycleStatus
608
+ });
609
+ if (fixture.planRevision !== 0)
610
+ repos.processes.update(process2.id, { planRevision: fixture.planRevision });
611
+ for (const project of input.projects ?? [])
612
+ repos.projects.create({
613
+ instanceId: process2.id,
614
+ key: project.key,
615
+ repoLocator: project.repoLocator,
616
+ baseBranch: project.baseBranch,
617
+ workBranch: project.workBranch,
618
+ metadata: project.metadata,
619
+ externalId: project.externalId,
620
+ externalUrl: project.externalUrl,
621
+ pipelineStatus: project.pipelineStatus
622
+ });
623
+ return process2;
624
+ });
625
+ if (fixture.lifecycleStatus === "active" && fixture.selectedTurnId) {
626
+ const result = await deps.processEngine.startProcess(process.id, fixture.selectedTurnId);
627
+ if (!result.ok) throw new Error(`Process start failed: ${result.message}`);
628
+ }
629
+ return processHandle(process.id);
630
+ },
631
+ /** Reopen the same file-backed storage and retain existing handles. @public */
632
+ async restart(restartOptions = {}) {
633
+ if (executing.size) throw new Error("Cannot restart during runTurn");
634
+ const { deps } = context();
635
+ const paused = manual ? deps.processes.listAll().flatMap((process) => {
636
+ if (process.lifecycleStatus !== "active" || process.currentExecution?.kind !== "worker_start")
637
+ return [];
638
+ const start = deps.turnStarts.getById(process.currentExecution.id);
639
+ return start?.state.kind === "starting" ? [{ instanceId: process.id, startId: start.id }] : [];
640
+ }) : [];
641
+ await persistent.close();
642
+ if (restartOptions.extensionConfig)
643
+ options.extensionConfig = structuredClone(restartOptions.extensionConfig);
644
+ await restartOptions.whileStopped?.();
645
+ pending.clear();
646
+ permits.clear();
647
+ scripts.clear();
648
+ await open();
649
+ for (const pausedStart of paused) {
650
+ if (context().deps.processes.getById(pausedStart.instanceId)?.lifecycleStatus !== "error")
651
+ continue;
652
+ const result = await context().deps.processEngine.retryStartup(
653
+ pausedStart.instanceId,
654
+ pausedStart.startId
655
+ );
656
+ if (!result.ok)
657
+ throw new Error(`Cannot restore paused turn after restart: ${result.message}`);
658
+ }
659
+ },
660
+ /** Release all resources and remove harness-owned files. @public */
661
+ async close() {
662
+ if (closed) return;
663
+ closed = true;
664
+ try {
665
+ await persistent.dispose();
666
+ } finally {
667
+ pending.clear();
668
+ permits.clear();
669
+ scripts.clear();
670
+ }
671
+ }
672
+ };
673
+ }
674
+
114
675
  // src/polling.ts
115
676
  async function waitForValue(read, predicate, timeoutMs = 5e3) {
116
677
  const deadline = Date.now() + timeoutMs;
@@ -176,6 +737,7 @@ function createProcessDriver(context) {
176
737
  };
177
738
  }
178
739
  export {
740
+ createExtensionIntegrationHarness,
179
741
  createIntegrationHarness,
180
742
  createPersistentIntegrationFixture,
181
743
  createProcessDriver,