@leitwerk-dev/test-support 0.1.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 (131) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/chunk-22HCVJEE.js +294 -0
  3. package/dist/chunk-22HCVJEE.js.map +1 -0
  4. package/dist/chunk-3MQO3NCX.js +15 -0
  5. package/dist/chunk-3MQO3NCX.js.map +1 -0
  6. package/dist/chunk-7ZK5QRGP.js +98 -0
  7. package/dist/chunk-7ZK5QRGP.js.map +1 -0
  8. package/dist/chunk-JUH3LUYK.js +28 -0
  9. package/dist/chunk-JUH3LUYK.js.map +1 -0
  10. package/dist/chunk-KIDBCGNW.js +84 -0
  11. package/dist/chunk-KIDBCGNW.js.map +1 -0
  12. package/dist/chunk-QFCJV2VA.js +600 -0
  13. package/dist/chunk-QFCJV2VA.js.map +1 -0
  14. package/dist/chunk-R4KVUGWR.js +83 -0
  15. package/dist/chunk-R4KVUGWR.js.map +1 -0
  16. package/dist/compact-process-detail-fixture.d.ts +6 -0
  17. package/dist/compact-process-detail-fixture.d.ts.map +1 -0
  18. package/dist/compact-process-detail-fixture.js +73 -0
  19. package/dist/compact-process-detail-fixture.js.map +1 -0
  20. package/dist/fakes/fake-git-ops.d.ts +22 -0
  21. package/dist/fakes/fake-git-ops.d.ts.map +1 -0
  22. package/dist/fakes/fake-git-ops.js +101 -0
  23. package/dist/fakes/fake-git-ops.js.map +1 -0
  24. package/dist/fakes/fake-llm.d.ts +21 -0
  25. package/dist/fakes/fake-llm.d.ts.map +1 -0
  26. package/dist/fakes/fake-llm.js +27 -0
  27. package/dist/fakes/fake-llm.js.map +1 -0
  28. package/dist/fakes/index.d.ts +3 -0
  29. package/dist/fakes/index.d.ts.map +1 -0
  30. package/dist/fakes/index.js +3 -0
  31. package/dist/fakes/index.js.map +1 -0
  32. package/dist/fixtures.d.ts +3 -0
  33. package/dist/fixtures.d.ts.map +1 -0
  34. package/dist/fixtures.js +3 -0
  35. package/dist/fixtures.js.map +1 -0
  36. package/dist/in-process-worker.d.ts +2 -0
  37. package/dist/in-process-worker.d.ts.map +1 -0
  38. package/dist/in-process-worker.js +2 -0
  39. package/dist/in-process-worker.js.map +1 -0
  40. package/dist/index.d.ts +13 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +13 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/integration-harness.d.ts +21 -0
  45. package/dist/integration-harness.d.ts.map +1 -0
  46. package/dist/integration-harness.js +38 -0
  47. package/dist/integration-harness.js.map +1 -0
  48. package/dist/integration.d.ts +5 -0
  49. package/dist/integration.d.ts.map +1 -0
  50. package/dist/integration.js +5 -0
  51. package/dist/integration.js.map +1 -0
  52. package/dist/polling.d.ts +2 -0
  53. package/dist/polling.d.ts.map +1 -0
  54. package/dist/polling.js +14 -0
  55. package/dist/polling.js.map +1 -0
  56. package/dist/question-fixtures.d.ts +4 -0
  57. package/dist/question-fixtures.d.ts.map +1 -0
  58. package/dist/question-fixtures.js +26 -0
  59. package/dist/question-fixtures.js.map +1 -0
  60. package/dist/server-extension-test-harness.d.ts +31 -0
  61. package/dist/server-extension-test-harness.d.ts.map +1 -0
  62. package/dist/server-extension-test-harness.js +167 -0
  63. package/dist/server-extension-test-harness.js.map +1 -0
  64. package/dist/stub-worker-entry.d.ts +2 -0
  65. package/dist/stub-worker-entry.d.ts.map +1 -0
  66. package/dist/stub-worker-entry.js +10 -0
  67. package/dist/stub-worker-entry.js.map +1 -0
  68. package/dist/test-app.d.ts +23 -0
  69. package/dist/test-app.d.ts.map +1 -0
  70. package/dist/test-app.js +47 -0
  71. package/dist/test-app.js.map +1 -0
  72. package/dist/worker-testing/in-process-worker-spawn.d.ts +15 -0
  73. package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -0
  74. package/dist/worker-testing/in-process-worker-spawn.js +61 -0
  75. package/dist/worker-testing/in-process-worker-spawn.js.map +1 -0
  76. package/dist/worker-testing/index.d.ts +8 -0
  77. package/dist/worker-testing/index.d.ts.map +1 -0
  78. package/dist/worker-testing/index.js +8 -0
  79. package/dist/worker-testing/index.js.map +1 -0
  80. package/dist/worker-testing/ipc-harness.d.ts +11 -0
  81. package/dist/worker-testing/ipc-harness.d.ts.map +1 -0
  82. package/dist/worker-testing/ipc-harness.js +17 -0
  83. package/dist/worker-testing/ipc-harness.js.map +1 -0
  84. package/dist/worker-testing/schema-driven-stub-pi.d.ts +8 -0
  85. package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -0
  86. package/dist/worker-testing/schema-driven-stub-pi.js +65 -0
  87. package/dist/worker-testing/schema-driven-stub-pi.js.map +1 -0
  88. package/dist/worker-testing/stub-pi-controls.d.ts +7 -0
  89. package/dist/worker-testing/stub-pi-controls.d.ts.map +1 -0
  90. package/dist/worker-testing/stub-pi-controls.js +10 -0
  91. package/dist/worker-testing/stub-pi-controls.js.map +1 -0
  92. package/dist/worker-testing/stub-pi-tree-handle.d.ts +92 -0
  93. package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -0
  94. package/dist/worker-testing/stub-pi-tree-handle.js +515 -0
  95. package/dist/worker-testing/stub-pi-tree-handle.js.map +1 -0
  96. package/dist/worker-testing/worker-runtime-harness.d.ts +53 -0
  97. package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -0
  98. package/dist/worker-testing/worker-runtime-harness.js +210 -0
  99. package/dist/worker-testing/worker-runtime-harness.js.map +1 -0
  100. package/dist/worker-testing/worker-start-payload.d.ts +25 -0
  101. package/dist/worker-testing/worker-start-payload.d.ts.map +1 -0
  102. package/dist/worker-testing/worker-start-payload.js +101 -0
  103. package/dist/worker-testing/worker-start-payload.js.map +1 -0
  104. package/dist/workspace-source-aliases.d.ts +6 -0
  105. package/dist/workspace-source-aliases.d.ts.map +1 -0
  106. package/dist/workspace-source-aliases.js +126 -0
  107. package/dist/workspace-source-aliases.js.map +1 -0
  108. package/package.json +66 -0
  109. package/src/compact-process-detail-fixture.ts +117 -0
  110. package/src/fakes/fake-git-ops.ts +109 -0
  111. package/src/fakes/fake-llm.ts +39 -0
  112. package/src/fakes/index.ts +2 -0
  113. package/src/fixtures.ts +2 -0
  114. package/src/in-process-worker.ts +4 -0
  115. package/src/index.ts +45 -0
  116. package/src/integration-harness.ts +75 -0
  117. package/src/integration.ts +14 -0
  118. package/src/polling.ts +17 -0
  119. package/src/question-fixtures.ts +32 -0
  120. package/src/server-extension-test-harness.ts +204 -0
  121. package/src/stub-worker-entry.ts +11 -0
  122. package/src/test-app.ts +82 -0
  123. package/src/worker-testing/in-process-worker-spawn.ts +84 -0
  124. package/src/worker-testing/index.ts +36 -0
  125. package/src/worker-testing/ipc-harness.ts +19 -0
  126. package/src/worker-testing/schema-driven-stub-pi.ts +83 -0
  127. package/src/worker-testing/stub-pi-controls.ts +16 -0
  128. package/src/worker-testing/stub-pi-tree-handle.ts +687 -0
  129. package/src/worker-testing/worker-runtime-harness.ts +280 -0
  130. package/src/worker-testing/worker-start-payload.ts +135 -0
  131. package/src/workspace-source-aliases.ts +171 -0
@@ -0,0 +1,117 @@
1
+ import type {
2
+ ProcessEvent,
3
+ ProcessInput,
4
+ ProcessInstance,
5
+ ProcessProject,
6
+ ProcessTurnAnnotation,
7
+ ProcessTurnRecord,
8
+ WorkerLease,
9
+ } from "@leitwerk-dev/domain";
10
+ import {
11
+ createReadonlyEntryTree,
12
+ type PiSessionEntry,
13
+ type ProcessDetailUiSnapshotResponseBody,
14
+ type TurnReasoningDetailResponseBody,
15
+ type TurnTraceSnapshot,
16
+ } from "@leitwerk-dev/protocol";
17
+ import {
18
+ buildProcessUiSnapshotProjections,
19
+ buildTurnTraceIndexFromSession,
20
+ type ReadonlyPiSessionTree,
21
+ } from "@leitwerk-dev/server/testing";
22
+
23
+ type LegacyProcessDetailFixture = ProcessDetailUiSnapshotResponseBody & {
24
+ process: ProcessInstance;
25
+ projects: ProcessProject[];
26
+ inputs: ProcessInput[];
27
+ events: ProcessEvent[];
28
+ turnRecords: ProcessTurnRecord[];
29
+ turnAnnotations: ProcessTurnAnnotation[];
30
+ workerLease: WorkerLease | null;
31
+ piSessionEntries: PiSessionEntry[];
32
+ };
33
+
34
+ const EMPTY_TRACE: TurnTraceSnapshot = {
35
+ assistant: { text: "", thinking: "", lastUpdatedAt: null },
36
+ toolCalls: [],
37
+ traceItems: [],
38
+ usage: null,
39
+ piInput: null,
40
+ };
41
+
42
+ export function createCompactProcessDetailFixtureFactory() {
43
+ const reasoningSourceByInstanceId = new Map<
44
+ string,
45
+ {
46
+ signature: string | null;
47
+ traceIndex: Record<string, TurnTraceSnapshot>;
48
+ }
49
+ >();
50
+
51
+ function compact(input: unknown): ProcessDetailUiSnapshotResponseBody {
52
+ const legacy = input as LegacyProcessDetailFixture;
53
+ if (!Array.isArray(legacy.turnRecords)) {
54
+ return input as ProcessDetailUiSnapshotResponseBody;
55
+ }
56
+ const sessionEntries = legacy.piSessionEntries ?? [];
57
+ const entryTree = createReadonlyEntryTree(sessionEntries);
58
+ const sessionTree = {
59
+ ...entryTree,
60
+ treeFile: "ui-compact-fixture",
61
+ header: null,
62
+ getTree: () => [],
63
+ } as unknown as ReadonlyPiSessionTree;
64
+ const traceIndex = buildTurnTraceIndexFromSession({
65
+ tree: sessionTree,
66
+ turnRecords: legacy.turnRecords,
67
+ events: legacy.events,
68
+ });
69
+ const signature =
70
+ sessionEntries.length > 0 ? `test-session:${JSON.stringify(sessionEntries).length}` : null;
71
+ const projections = buildProcessUiSnapshotProjections({
72
+ process: legacy.process,
73
+ turnRecords: legacy.turnRecords,
74
+ turnAnnotations: legacy.turnAnnotations,
75
+ events: legacy.events,
76
+ inputs: legacy.inputs,
77
+ selectedTurn: legacy.selectedTurn ?? null,
78
+ primaryPathSnapshot: legacy.primaryPath,
79
+ sessionTree,
80
+ });
81
+ const compactDetail: ProcessDetailUiSnapshotResponseBody = {
82
+ ...projections,
83
+ instanceTree: legacy.instanceTree ?? { currentLeafId: null, nodes: [], edges: [] },
84
+ leafOutcomeSnapshots: legacy.leafOutcomeSnapshots,
85
+ questionRequests: [],
86
+ processDisplayName: legacy.processDisplayName,
87
+ processFlow: legacy.processFlow,
88
+ definesLeafOutcome: legacy.definesLeafOutcome,
89
+ selectedTurn: legacy.selectedTurn ?? null,
90
+ scheduledAction: legacy.scheduledAction ?? null,
91
+ modelConfiguration: legacy.modelConfiguration,
92
+ runDetails: legacy.runDetails,
93
+ launchConfiguration: legacy.launchConfiguration,
94
+ actions: legacy.actions,
95
+ toolRenderers: legacy.toolRenderers,
96
+ persistedModelSelectionWarning: null,
97
+ session: { signature },
98
+ };
99
+ reasoningSourceByInstanceId.set(projections.process.id, { signature, traceIndex });
100
+ return compactDetail;
101
+ }
102
+
103
+ function reasoningResponse(
104
+ instanceId: string,
105
+ turnRecordId: string,
106
+ ): TurnReasoningDetailResponseBody {
107
+ const source = reasoningSourceByInstanceId.get(instanceId);
108
+ return {
109
+ instanceId,
110
+ turnRecordId,
111
+ sessionSignature: source?.signature ?? null,
112
+ reasoning: source?.traceIndex[turnRecordId] ?? EMPTY_TRACE,
113
+ };
114
+ }
115
+
116
+ return { compact, reasoningResponse };
117
+ }
@@ -0,0 +1,109 @@
1
+ import path from "node:path";
2
+
3
+ export type RepoTemplate = Record<string, string>;
4
+
5
+ /**
6
+ * Structurally compatible with RunRootGitOps — call sites annotate
7
+ * `const git: RunRootGitOps = new FakeGitOps(...)` so TS catches drift.
8
+ */
9
+ export class FakeGitOps {
10
+ readonly operations: string[] = [];
11
+ private readonly files = new Map<string, string>();
12
+ private readonly repoState = new Map<string, { currentBranch: string; branches: Set<string> }>();
13
+
14
+ constructor(private readonly templates: Map<string, RepoTemplate>) {}
15
+
16
+ private abs(repoDir: string, filePath: string): string {
17
+ return path.normalize(path.join(repoDir, filePath));
18
+ }
19
+
20
+ async writeFile(repoDir: string, filePath: string, content: string): Promise<void> {
21
+ this.operations.push(`writeFile:${filePath}`);
22
+ this.files.set(this.abs(repoDir, filePath), content);
23
+ }
24
+
25
+ async readFile(repoDir: string, filePath: string): Promise<string | null> {
26
+ return this.files.get(this.abs(repoDir, filePath)) ?? null;
27
+ }
28
+
29
+ async clone(repoLocator: string, targetDir: string): Promise<void> {
30
+ this.operations.push(`clone:${path.basename(targetDir)}`);
31
+ const n = path.normalize(targetDir);
32
+ const prefix = n + path.sep;
33
+ for (const k of [...this.files.keys()]) {
34
+ if (k === n || k.startsWith(prefix)) {
35
+ this.files.delete(k);
36
+ }
37
+ }
38
+ const tmpl = this.templates.get(repoLocator);
39
+ if (!tmpl) {
40
+ throw new Error(`unknown repo ${repoLocator}`);
41
+ }
42
+ for (const [rel, content] of Object.entries(tmpl)) {
43
+ this.files.set(path.join(targetDir, rel), content);
44
+ }
45
+ this.repoState.set(n, {
46
+ currentBranch: "main",
47
+ branches: new Set(["main"]),
48
+ });
49
+ }
50
+
51
+ async checkout(repoDir: string, branch: string): Promise<void> {
52
+ const st = this.repoState.get(path.normalize(repoDir));
53
+ if (!st) {
54
+ throw new Error("not a repo");
55
+ }
56
+ st.branches.add(branch);
57
+ st.currentBranch = branch;
58
+ }
59
+
60
+ async createBranch(repoDir: string, branchName: string, _startPoint: string): Promise<void> {
61
+ const st = this.repoState.get(path.normalize(repoDir));
62
+ if (!st) {
63
+ throw new Error("not a repo");
64
+ }
65
+ st.branches.add(branchName);
66
+ }
67
+
68
+ async branchExists(repoDir: string, branchName: string): Promise<boolean> {
69
+ const st = this.repoState.get(path.normalize(repoDir));
70
+ return st?.branches.has(branchName) ?? false;
71
+ }
72
+
73
+ async getHeadSha(repoDir: string): Promise<string> {
74
+ const st = this.repoState.get(path.normalize(repoDir));
75
+ if (!st) {
76
+ throw new Error("not a repo");
77
+ }
78
+ return Buffer.from(`${repoDir}:${st.currentBranch}`)
79
+ .toString("hex")
80
+ .slice(0, 40)
81
+ .padEnd(40, "0");
82
+ }
83
+
84
+ async listFiles(repoDir: string, pattern: string): Promise<string[]> {
85
+ const normRoot = path.normalize(repoDir);
86
+ const prefix = normRoot + path.sep;
87
+ const out: string[] = [];
88
+ for (const k of this.files.keys()) {
89
+ if (k !== normRoot && !k.startsWith(prefix)) {
90
+ continue;
91
+ }
92
+ const rel = k === normRoot ? "" : k.slice(prefix.length);
93
+ if (!rel) {
94
+ continue;
95
+ }
96
+ const relPosix = rel.split(path.sep).join("/");
97
+ if (pattern === "**/AGENTS.md") {
98
+ if (relPosix.endsWith("AGENTS.md")) {
99
+ out.push(relPosix);
100
+ }
101
+ } else if (pattern === "**/.cursor/skills/**/SKILL.md") {
102
+ if (/^\.cursor\/skills\/[^/]+\/SKILL\.md$/.test(relPosix)) {
103
+ out.push(relPosix);
104
+ }
105
+ }
106
+ }
107
+ return out.sort((a, b) => a.localeCompare(b));
108
+ }
109
+ }
@@ -0,0 +1,39 @@
1
+ export interface LlmResponse {
2
+ content: string;
3
+ toolCalls?: Array<{
4
+ name: string;
5
+ arguments: Record<string, unknown>;
6
+ }>;
7
+ }
8
+
9
+ export type LlmHandler = (prompt: string) => LlmResponse;
10
+
11
+ /**
12
+ * Deterministic in-memory LLM fake for automated system tests.
13
+ * Responds with scripted outputs based on registered handlers.
14
+ */
15
+ export class FakeLlmProvider {
16
+ private handlers: LlmHandler[] = [];
17
+ private callIndex = 0;
18
+ readonly calls: string[] = [];
19
+
20
+ onPrompt(handler: LlmHandler): void {
21
+ this.handlers.push(handler);
22
+ }
23
+
24
+ respond(prompt: string): LlmResponse {
25
+ this.calls.push(prompt);
26
+ const handler = this.handlers[this.callIndex % this.handlers.length];
27
+ if (handler) {
28
+ this.callIndex++;
29
+ return handler(prompt);
30
+ }
31
+ return { content: "No handler registered for this prompt." };
32
+ }
33
+
34
+ reset(): void {
35
+ this.handlers = [];
36
+ this.callIndex = 0;
37
+ this.calls.length = 0;
38
+ }
39
+ }
@@ -0,0 +1,2 @@
1
+ export { FakeGitOps, type RepoTemplate } from "./fake-git-ops.js";
2
+ export { FakeLlmProvider, type LlmResponse } from "./fake-llm.js";
@@ -0,0 +1,2 @@
1
+ export { createCompactProcessDetailFixtureFactory } from "./compact-process-detail-fixture.js";
2
+ export { createTestQuestion, createTestQuestionRequest } from "./question-fixtures.js";
@@ -0,0 +1,4 @@
1
+ export {
2
+ createInProcessWorkerSpawn,
3
+ type InProcessWorkerSpawnOptions,
4
+ } from "./worker-testing/in-process-worker-spawn.js";
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ export { createCompactProcessDetailFixtureFactory } from "./compact-process-detail-fixture.js";
2
+ export { FakeGitOps, type RepoTemplate } from "./fakes/fake-git-ops.js";
3
+ export { FakeLlmProvider, type LlmResponse } from "./fakes/fake-llm.js";
4
+ export {
5
+ createInProcessWorkerSpawn,
6
+ type InProcessWorkerSpawnOptions,
7
+ } from "./in-process-worker.js";
8
+ export {
9
+ createIntegrationHarness,
10
+ type IntegrationHarness,
11
+ type IntegrationHarnessOptions,
12
+ } from "./integration-harness.js";
13
+ export { waitForValue } from "./polling.js";
14
+ export {
15
+ createInMemoryExternalWriteLog,
16
+ createTestServerSetupCapability,
17
+ type InMemoryExternalWriteLog,
18
+ type ServerExtensionTestHarness,
19
+ setupServerExtensionTest,
20
+ } from "./server-extension-test-harness.js";
21
+ export { createTestApp, type TestApp, type TestAppOptions } from "./test-app.js";
22
+ export {
23
+ baseEnvelope,
24
+ flushAsyncWork,
25
+ testConfigSnapshot,
26
+ } from "./worker-testing/ipc-harness.js";
27
+ export {
28
+ createSchemaDrivenStubPiFactory,
29
+ createSchemaDrivenToolCallScriptResolver,
30
+ synthesizeStubArgValue,
31
+ synthesizeStubToolArgs,
32
+ } from "./worker-testing/schema-driven-stub-pi.js";
33
+ export {
34
+ createStubToolScriptController,
35
+ type StubToolScriptController,
36
+ } from "./worker-testing/stub-pi-controls.js";
37
+ export {
38
+ StubPiTreeHandle,
39
+ StubPiTreeHandleFactory,
40
+ type StubPiTreeHandleFactoryOptions,
41
+ type StubToolCallScriptCall,
42
+ type StubToolCallScriptItem,
43
+ type StubToolCallScriptResolver,
44
+ type StubToolCallScriptResolverContext,
45
+ } from "./worker-testing/stub-pi-tree-handle.js";
@@ -0,0 +1,75 @@
1
+ import type { ExtensionCatalog } from "@leitwerk-dev/extension-runtime";
2
+ import type { ProvidedCapability } from "@leitwerk-dev/process-sdk";
3
+ import {
4
+ type AppContext,
5
+ type AppOptions,
6
+ createAppContext,
7
+ getDefaultConfig,
8
+ type LeitwerkConfig,
9
+ } from "@leitwerk-dev/server";
10
+ import { createInProcessWorkerSpawn } from "./in-process-worker.js";
11
+
12
+ export interface IntegrationHarness<
13
+ TResources extends Record<string, unknown> = Record<string, never>,
14
+ > {
15
+ ctx: AppContext;
16
+ config: LeitwerkConfig;
17
+ address: string;
18
+ resources: TResources;
19
+ }
20
+
21
+ export interface IntegrationHarnessOptions<
22
+ TResources extends Record<string, unknown> = Record<string, never>,
23
+ > {
24
+ config?: LeitwerkConfig;
25
+ configOverride?: (config: LeitwerkConfig) => void;
26
+ appOverrides?: Partial<AppOptions>;
27
+ listen?: boolean;
28
+ inProcessWorkers?: boolean;
29
+ extensionCatalog: ExtensionCatalog | Promise<ExtensionCatalog>;
30
+ preProvidedCapabilities?: readonly ProvidedCapability[];
31
+ resources?: TResources;
32
+ }
33
+
34
+ export async function createIntegrationHarness<
35
+ TResources extends Record<string, unknown> = Record<string, never>,
36
+ >(opts: IntegrationHarnessOptions<TResources>): Promise<IntegrationHarness<TResources>> {
37
+ const config = opts.config ?? getDefaultConfig();
38
+ if (!opts.appOverrides?.workerRunnerRuntime) {
39
+ config.workers.runner = "local";
40
+ }
41
+ opts.configOverride?.(config);
42
+
43
+ const extensionCatalog = await Promise.resolve(opts.extensionCatalog);
44
+
45
+ const appOpts: AppOptions = {
46
+ logger: false,
47
+ config,
48
+ extensionCatalog,
49
+ preProvidedCapabilities: opts.preProvidedCapabilities,
50
+ ...opts.appOverrides,
51
+ };
52
+
53
+ if (opts.inProcessWorkers !== false && !appOpts.localWorkerSpawnImpl) {
54
+ appOpts.localWorkerSpawnImpl = createInProcessWorkerSpawn({
55
+ extensionCatalog,
56
+ });
57
+ }
58
+ const ctx = await createAppContext(appOpts);
59
+
60
+ let address = "";
61
+ if (opts.listen !== false || config.workers.runner === "local") {
62
+ await ctx.app.listen({ host: "127.0.0.1", port: 0 });
63
+ const info = ctx.app.server.address();
64
+ const port = typeof info === "object" && info ? info.port : 0;
65
+ address = `http://127.0.0.1:${port}`;
66
+ ctx.config.server.base_url = address;
67
+ }
68
+
69
+ return {
70
+ ctx,
71
+ config,
72
+ address,
73
+ resources: opts.resources ?? ({} as TResources),
74
+ };
75
+ }
@@ -0,0 +1,14 @@
1
+ export {
2
+ createIntegrationHarness,
3
+ type IntegrationHarness,
4
+ type IntegrationHarnessOptions,
5
+ } from "./integration-harness.js";
6
+ export { waitForValue } from "./polling.js";
7
+ export {
8
+ createInMemoryExternalWriteLog,
9
+ createTestServerSetupCapability,
10
+ type InMemoryExternalWriteLog,
11
+ type ServerExtensionTestHarness,
12
+ setupServerExtensionTest,
13
+ } from "./server-extension-test-harness.js";
14
+ export { createTestApp, type TestApp, type TestAppOptions } from "./test-app.js";
package/src/polling.ts ADDED
@@ -0,0 +1,17 @@
1
+ export async function waitForValue<T>(
2
+ read: () => T,
3
+ predicate: (value: T) => boolean,
4
+ timeoutMs = 5_000,
5
+ ): Promise<T> {
6
+ const deadline = Date.now() + timeoutMs;
7
+ while (true) {
8
+ const value = read();
9
+ if (predicate(value)) {
10
+ return value;
11
+ }
12
+ if (Date.now() >= deadline) {
13
+ throw new Error("Timed out waiting for value");
14
+ }
15
+ await new Promise((resolve) => setTimeout(resolve, 25));
16
+ }
17
+ }
@@ -0,0 +1,32 @@
1
+ import type { NormalizedQuestion, ProcessQuestionRequest } from "@leitwerk-dev/domain";
2
+
3
+ export function createTestQuestion(
4
+ overrides: Partial<NormalizedQuestion> = {},
5
+ ): NormalizedQuestion {
6
+ return {
7
+ id: "question_1",
8
+ question: "Choose a strategy",
9
+ selection: "single",
10
+ options: [{ id: "question_1_option_1", label: "Safe", details: "Small change" }],
11
+ ...overrides,
12
+ };
13
+ }
14
+
15
+ export function createTestQuestionRequest(
16
+ overrides: Partial<ProcessQuestionRequest> = {},
17
+ ): ProcessQuestionRequest {
18
+ return {
19
+ id: "qst_1",
20
+ instanceId: "agt_1",
21
+ turnRecordId: "trn_1",
22
+ toolCallId: "tool_1",
23
+ questions: [createTestQuestion()],
24
+ status: "open",
25
+ answers: null,
26
+ askedAt: "2026-01-01T00:00:00.000Z",
27
+ answeredAt: null,
28
+ answeredBy: null,
29
+ cancelledAt: null,
30
+ ...overrides,
31
+ };
32
+ }
@@ -0,0 +1,204 @@
1
+ import { type ExtensionCatalog, setupServerExtensions } from "@leitwerk-dev/extension-runtime";
2
+ import { buildExtensionCatalogFromModules } from "@leitwerk-dev/extension-runtime/testing";
3
+ import {
4
+ type CoreServerSetupDeps,
5
+ coreHostCapabilities,
6
+ createCapabilityAccessor,
7
+ createEventBus,
8
+ type LeitwerkExtensionModule,
9
+ type ProvidedCapability,
10
+ type ServerExtensionEventMap,
11
+ } from "@leitwerk-dev/process-sdk";
12
+ import { flushAsyncWork } from "./worker-testing/ipc-harness.js";
13
+
14
+ export { flushAsyncWork };
15
+
16
+ export interface InMemoryExternalWriteLog {
17
+ hasDedupKey(key: string): boolean;
18
+ record(input: { dedupKey: string }): { dedupKey: string };
19
+ getDedupKeys(): ReadonlySet<string>;
20
+ }
21
+
22
+ export function createInMemoryExternalWriteLog(): InMemoryExternalWriteLog {
23
+ const dedupKeys = new Set<string>();
24
+ return {
25
+ hasDedupKey(key: string) {
26
+ return dedupKeys.has(key);
27
+ },
28
+ record(input: { dedupKey: string }) {
29
+ dedupKeys.add(input.dedupKey);
30
+ return input;
31
+ },
32
+ getDedupKeys() {
33
+ return dedupKeys;
34
+ },
35
+ };
36
+ }
37
+
38
+ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
39
+ return {
40
+ serverBaseUrl: "https://leitwerk.example",
41
+ components: {},
42
+ externalWrites: createInMemoryExternalWriteLog(),
43
+ repositoryCredentials: { register: () => {} },
44
+ processes: {
45
+ create: () => {
46
+ throw new Error("not used");
47
+ },
48
+ getById: () => null,
49
+ listAll: () => [],
50
+ },
51
+ projects: {
52
+ create: () => {
53
+ throw new Error("not used");
54
+ },
55
+ getByInstanceAndKey: () => null,
56
+ update: () => null,
57
+ listByInstance: () => [],
58
+ },
59
+ events: { create: () => {}, listByInstance: () => [] },
60
+ broadcaster: { sendDurable: () => {} },
61
+ commands: {
62
+ getDeferredProcessActivationSnapshots: () => ({ outcome: "process_not_found" }),
63
+ activateDeferredProcess: async () => ({
64
+ ok: true,
65
+ process: null,
66
+ data: { outcome: "not_applicable" },
67
+ }),
68
+ parkDeferredProcessActivationFailure: async () => ({
69
+ ok: true,
70
+ process: null,
71
+ data: { outcome: "parked" },
72
+ }),
73
+ startProcess: async () => ({ ok: true, process: null }),
74
+ abortProcess: async () => ({ ok: true, process: null }),
75
+ retryProcess: async () => ({ ok: true, process: null }),
76
+ continueFailedTurn: async () => ({ ok: true, process: null }),
77
+ queueInputs: async () => ({ ok: true, process: null }),
78
+ },
79
+ processActions: {
80
+ listVisibleActions: () => [],
81
+ executeAction: async () => ({ ok: true, process: null }),
82
+ },
83
+ externalSources: {
84
+ listArmed: () => [],
85
+ fire: async () => ({ ok: true, process: null }),
86
+ },
87
+ getSupervisor: () => undefined,
88
+ launcherService: {
89
+ listUiLaunchers: () => [],
90
+ resolveUiDefaults: async () => ({}),
91
+ resolveUiOptions: async () => ({}),
92
+ resolveUiRelaunchInput: async (_launcherId, previousInput) => ({ ...previousInput }),
93
+ resolveUiLauncher: async () => ({ ok: false as const, errors: [] }),
94
+ },
95
+ launcherRecentValues: {
96
+ list: () => ({}),
97
+ record: () => {},
98
+ },
99
+ launcherModelConfigs: {
100
+ getSchema: async () => null,
101
+ preview: async () => null,
102
+ },
103
+ launchPlans: {
104
+ async prepare(launchPlan, opts) {
105
+ return {
106
+ ok: true as const,
107
+ launchPlan,
108
+ modelConfig: opts?.modelConfig ?? {},
109
+ warnings: [],
110
+ };
111
+ },
112
+ },
113
+ processLaunches: {
114
+ async createProcessFromLaunchConfig() {
115
+ throw new Error("not used");
116
+ },
117
+ async createProcessFromLaunchPlan() {
118
+ throw new Error("not used");
119
+ },
120
+ },
121
+ };
122
+ }
123
+
124
+ export function createTestServerSetupCapability(
125
+ overrides: Partial<CoreServerSetupDeps> = {},
126
+ ): CoreServerSetupDeps {
127
+ const defaults = createDefaultServerSetupDeps();
128
+ return {
129
+ ...defaults,
130
+ ...overrides,
131
+ processes: { ...defaults.processes, ...overrides.processes },
132
+ projects: { ...defaults.projects, ...overrides.projects },
133
+ events: { ...defaults.events, ...overrides.events },
134
+ broadcaster: { ...defaults.broadcaster, ...overrides.broadcaster },
135
+ commands: { ...defaults.commands, ...overrides.commands },
136
+ processActions: { ...defaults.processActions, ...overrides.processActions },
137
+ externalSources: { ...defaults.externalSources, ...overrides.externalSources },
138
+ launcherService: { ...defaults.launcherService, ...overrides.launcherService },
139
+ launcherRecentValues: {
140
+ ...defaults.launcherRecentValues,
141
+ ...overrides.launcherRecentValues,
142
+ },
143
+ launcherModelConfigs: {
144
+ ...defaults.launcherModelConfigs,
145
+ ...overrides.launcherModelConfigs,
146
+ },
147
+ launchPlans: { ...defaults.launchPlans, ...overrides.launchPlans },
148
+ processLaunches: { ...defaults.processLaunches, ...overrides.processLaunches },
149
+ };
150
+ }
151
+
152
+ export interface ServerExtensionTestHarness {
153
+ catalog: ExtensionCatalog;
154
+ events: ReturnType<typeof createEventBus>;
155
+ serverSetup: CoreServerSetupDeps;
156
+ startHooks: Array<() => void | Promise<void>>;
157
+ stopHooks: Array<() => void | Promise<void>>;
158
+ flushAsyncWork: typeof flushAsyncWork;
159
+ }
160
+
161
+ export async function setupServerExtensionTest(input: {
162
+ modules: readonly LeitwerkExtensionModule[];
163
+ providedCapabilities?: readonly ProvidedCapability[];
164
+ serverSetup?: Partial<CoreServerSetupDeps>;
165
+ onStart?: (handler: () => void | Promise<void>) => void;
166
+ onStop?: (handler: () => void | Promise<void>) => void;
167
+ }): Promise<ServerExtensionTestHarness> {
168
+ const catalog = await buildExtensionCatalogFromModules(input.modules);
169
+ const events = createEventBus<ServerExtensionEventMap>();
170
+ const serverSetup = createTestServerSetupCapability(input.serverSetup);
171
+ const capabilities = createCapabilityAccessor([
172
+ {
173
+ token: coreHostCapabilities.serverSetup,
174
+ value: serverSetup,
175
+ },
176
+ ...(input.providedCapabilities ?? []),
177
+ ]);
178
+ const startHooks: Array<() => void | Promise<void>> = [];
179
+ const stopHooks: Array<() => void | Promise<void>> = [];
180
+
181
+ await setupServerExtensions(catalog, {
182
+ events,
183
+ provide: capabilities.provide.bind(capabilities),
184
+ get: capabilities.get.bind(capabilities),
185
+ require: capabilities.require.bind(capabilities),
186
+ onStart(handler) {
187
+ startHooks.push(handler);
188
+ input.onStart?.(handler);
189
+ },
190
+ onStop(handler) {
191
+ stopHooks.push(handler);
192
+ input.onStop?.(handler);
193
+ },
194
+ });
195
+
196
+ return {
197
+ catalog,
198
+ events,
199
+ serverSetup,
200
+ startHooks,
201
+ stopHooks,
202
+ flushAsyncWork,
203
+ };
204
+ }
@@ -0,0 +1,11 @@
1
+ import { createWorkerEntryRuntime } from "@leitwerk-dev/worker";
2
+ import { createSchemaDrivenStubPiFactory } from "./worker-testing/schema-driven-stub-pi.js";
3
+
4
+ const runtime = createWorkerEntryRuntime({
5
+ piFactory: createSchemaDrivenStubPiFactory(),
6
+ });
7
+
8
+ void runtime.start().catch((error: unknown) => {
9
+ console.error(error);
10
+ process.exit(1);
11
+ });