@leitwerk-dev/test-support 0.1.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/{chunk-KIDBCGNW.js → chunk-2PCDTYVH.js} +26 -26
  2. package/dist/chunk-2PCDTYVH.js.map +1 -0
  3. package/dist/chunk-5BZSJ4OO.js +192 -0
  4. package/dist/chunk-5BZSJ4OO.js.map +1 -0
  5. package/dist/{chunk-QFCJV2VA.js → chunk-ECAWLVYB.js} +224 -17
  6. package/dist/chunk-ECAWLVYB.js.map +1 -0
  7. package/dist/{chunk-JUH3LUYK.js → chunk-EXHTWQAE.js} +5 -1
  8. package/dist/chunk-EXHTWQAE.js.map +1 -0
  9. package/dist/compact-process-detail-fixture.d.ts +3 -0
  10. package/dist/compact-process-detail-fixture.d.ts.map +1 -1
  11. package/dist/fakes/fake-git-ops.d.ts +12 -0
  12. package/dist/fakes/fake-git-ops.d.ts.map +1 -1
  13. package/dist/fakes/fake-llm.d.ts +11 -0
  14. package/dist/fakes/fake-llm.d.ts.map +1 -1
  15. package/dist/fakes/index.d.ts +1 -1
  16. package/dist/fakes/index.d.ts.map +1 -1
  17. package/dist/fakes/index.js +111 -2
  18. package/dist/fakes/index.js.map +1 -1
  19. package/dist/fixtures.js +137 -2
  20. package/dist/fixtures.js.map +1 -1
  21. package/dist/http-launch.d.ts +9 -0
  22. package/dist/http-launch.d.ts.map +1 -0
  23. package/dist/index.d.ts +24 -12
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +113 -12
  26. package/dist/index.js.map +1 -1
  27. package/dist/integration-harness.d.ts +36 -1
  28. package/dist/integration-harness.d.ts.map +1 -1
  29. package/dist/integration.d.ts +3 -3
  30. package/dist/integration.d.ts.map +1 -1
  31. package/dist/integration.js +184 -4
  32. package/dist/integration.js.map +1 -1
  33. package/dist/local-git.d.ts +231 -0
  34. package/dist/local-git.d.ts.map +1 -0
  35. package/dist/local-git.js +428 -0
  36. package/dist/local-git.js.map +1 -0
  37. package/dist/model-provider-fixtures.d.ts +15 -0
  38. package/dist/model-provider-fixtures.d.ts.map +1 -0
  39. package/dist/polling.d.ts +2 -1
  40. package/dist/polling.d.ts.map +1 -1
  41. package/dist/process-driver.d.ts +14 -0
  42. package/dist/process-driver.d.ts.map +1 -0
  43. package/dist/question-fixtures.d.ts +2 -0
  44. package/dist/question-fixtures.d.ts.map +1 -1
  45. package/dist/server-extension-test-harness.d.ts +57 -2
  46. package/dist/server-extension-test-harness.d.ts.map +1 -1
  47. package/dist/stub-worker-entry.js +9 -5
  48. package/dist/stub-worker-entry.js.map +1 -1
  49. package/dist/test-diagnostics.d.ts +14 -0
  50. package/dist/test-diagnostics.d.ts.map +1 -0
  51. package/dist/worker-testing/in-process-worker-spawn.d.ts +21 -0
  52. package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -1
  53. package/dist/worker-testing/index.d.ts +6 -7
  54. package/dist/worker-testing/index.d.ts.map +1 -1
  55. package/dist/worker-testing/index.js +381 -7
  56. package/dist/worker-testing/index.js.map +1 -1
  57. package/dist/worker-testing/schema-driven-stub-pi.d.ts +5 -0
  58. package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -1
  59. package/dist/worker-testing/stub-pi-controls.d.ts +4 -0
  60. package/dist/worker-testing/stub-pi-controls.d.ts.map +1 -1
  61. package/dist/worker-testing/stub-pi-tree-handle.d.ts +93 -1
  62. package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
  63. package/dist/worker-testing/worker-runtime-harness.d.ts +37 -2
  64. package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -1
  65. package/dist/worker-testing/worker-start-payload.d.ts +17 -1
  66. package/dist/worker-testing/worker-start-payload.d.ts.map +1 -1
  67. package/package.json +15 -9
  68. package/src/compact-process-detail-fixture.ts +37 -3
  69. package/src/fakes/fake-git-ops.ts +12 -0
  70. package/src/fakes/fake-llm.ts +11 -0
  71. package/src/fakes/index.ts +1 -1
  72. package/src/http-launch.ts +88 -0
  73. package/src/index.ts +31 -41
  74. package/src/integration-harness.ts +100 -9
  75. package/src/integration.ts +3 -9
  76. package/src/local-git.ts +499 -0
  77. package/src/model-provider-fixtures.ts +36 -0
  78. package/src/polling.ts +3 -2
  79. package/src/process-driver.ts +63 -0
  80. package/src/question-fixtures.ts +2 -0
  81. package/src/server-extension-test-harness.ts +100 -6
  82. package/src/test-diagnostics.ts +69 -0
  83. package/src/worker-testing/in-process-worker-spawn.ts +49 -2
  84. package/src/worker-testing/index.ts +4 -26
  85. package/src/worker-testing/schema-driven-stub-pi.ts +8 -1
  86. package/src/worker-testing/stub-pi-controls.ts +4 -0
  87. package/src/worker-testing/stub-pi-tree-handle.ts +301 -21
  88. package/src/worker-testing/worker-runtime-harness.ts +57 -6
  89. package/src/worker-testing/worker-start-payload.ts +18 -1
  90. package/dist/chunk-3MQO3NCX.js +0 -15
  91. package/dist/chunk-3MQO3NCX.js.map +0 -1
  92. package/dist/chunk-7ZK5QRGP.js +0 -98
  93. package/dist/chunk-7ZK5QRGP.js.map +0 -1
  94. package/dist/chunk-JUH3LUYK.js.map +0 -1
  95. package/dist/chunk-KIDBCGNW.js.map +0 -1
  96. package/dist/chunk-QFCJV2VA.js.map +0 -1
  97. package/dist/chunk-R4KVUGWR.js +0 -83
  98. package/dist/chunk-R4KVUGWR.js.map +0 -1
  99. package/dist/chunk-ST2C4VKX.js +0 -297
  100. package/dist/chunk-ST2C4VKX.js.map +0 -1
  101. package/dist/compact-process-detail-fixture.js +0 -73
  102. package/dist/compact-process-detail-fixture.js.map +0 -1
  103. package/dist/fakes/fake-git-ops.js +0 -101
  104. package/dist/fakes/fake-git-ops.js.map +0 -1
  105. package/dist/fakes/fake-llm.js +0 -27
  106. package/dist/fakes/fake-llm.js.map +0 -1
  107. package/dist/in-process-worker.js +0 -2
  108. package/dist/in-process-worker.js.map +0 -1
  109. package/dist/integration-harness.js +0 -38
  110. package/dist/integration-harness.js.map +0 -1
  111. package/dist/polling.js +0 -14
  112. package/dist/polling.js.map +0 -1
  113. package/dist/question-fixtures.js +0 -26
  114. package/dist/question-fixtures.js.map +0 -1
  115. package/dist/server-extension-test-harness.js +0 -169
  116. package/dist/server-extension-test-harness.js.map +0 -1
  117. package/dist/test-app.d.ts +0 -23
  118. package/dist/test-app.d.ts.map +0 -1
  119. package/dist/test-app.js +0 -47
  120. package/dist/test-app.js.map +0 -1
  121. package/dist/worker-testing/in-process-worker-spawn.js +0 -61
  122. package/dist/worker-testing/in-process-worker-spawn.js.map +0 -1
  123. package/dist/worker-testing/ipc-harness.d.ts +0 -11
  124. package/dist/worker-testing/ipc-harness.d.ts.map +0 -1
  125. package/dist/worker-testing/ipc-harness.js +0 -17
  126. package/dist/worker-testing/ipc-harness.js.map +0 -1
  127. package/dist/worker-testing/schema-driven-stub-pi.js +0 -65
  128. package/dist/worker-testing/schema-driven-stub-pi.js.map +0 -1
  129. package/dist/worker-testing/stub-pi-controls.js +0 -10
  130. package/dist/worker-testing/stub-pi-controls.js.map +0 -1
  131. package/dist/worker-testing/stub-pi-tree-handle.js +0 -515
  132. package/dist/worker-testing/stub-pi-tree-handle.js.map +0 -1
  133. package/dist/worker-testing/worker-runtime-harness.js +0 -231
  134. package/dist/worker-testing/worker-runtime-harness.js.map +0 -1
  135. package/dist/worker-testing/worker-start-payload.js +0 -101
  136. package/dist/worker-testing/worker-start-payload.js.map +0 -1
  137. package/dist/workspace-source-aliases.d.ts +0 -6
  138. package/dist/workspace-source-aliases.d.ts.map +0 -1
  139. package/dist/workspace-source-aliases.js +0 -126
  140. package/dist/workspace-source-aliases.js.map +0 -1
  141. package/src/test-app.ts +0 -82
  142. package/src/worker-testing/ipc-harness.ts +0 -19
  143. package/src/workspace-source-aliases.ts +0 -171
@@ -0,0 +1,499 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import {
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ realpathSync,
8
+ renameSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import path from "node:path";
12
+ import type { RepositoryFeedbackItem, RepositoryPullRequest } from "@leitwerk-dev/process-sdk";
13
+ import { traceTestSubprocess } from "./test-diagnostics.js";
14
+
15
+ export { createTestDiagnostics } from "./test-diagnostics.js";
16
+
17
+ /** @public */
18
+ export interface LocalRepositorySeed {
19
+ /** @public */
20
+ owner: string;
21
+ /** @public */
22
+ name: string;
23
+ /** @internal */
24
+ defaultBranch?: string;
25
+ /** @public */
26
+ files?: Record<string, string>;
27
+ /** Retain a pre-existing sandbox checkout layout. @internal */
28
+ directoryName?: string;
29
+ /** @internal */
30
+ commitMessage?: string;
31
+ /** @internal */
32
+ signoff?: boolean;
33
+ }
34
+
35
+ /** Reject escaping paths and symlinks, including a not-yet-created file's parents. @public */
36
+ export function localPath(root: string, relative: string): string {
37
+ if (lstatSync(root, { throwIfNoEntry: false })?.isSymbolicLink())
38
+ throw new Error("Local provider storage must not contain symlinks");
39
+ const base = realpathSync(root);
40
+ const target = path.resolve(base, relative);
41
+ if (!target.startsWith(`${base}${path.sep}`))
42
+ throw new Error("Path escapes local provider storage");
43
+ let current = base;
44
+ for (const part of path.relative(base, target).split(path.sep)) {
45
+ current = path.join(current, part);
46
+ if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink())
47
+ throw new Error("Local provider storage must not contain symlinks");
48
+ }
49
+ return target;
50
+ }
51
+
52
+ /** @public */
53
+ export function readLocalJson<
54
+ T extends {
55
+ /** @internal */
56
+ version: number;
57
+ },
58
+ >(root: string, file: string, initial: T): T {
59
+ const target = localPath(root, file);
60
+ if (!existsSync(target)) return structuredClone(initial);
61
+ const value = JSON.parse(readFileSync(target, "utf8")) as T;
62
+ if (!value || value.version !== initial.version)
63
+ throw new Error(`Unsupported local state version in ${file}`);
64
+ return value;
65
+ }
66
+
67
+ /** @public */
68
+ export function writeLocalJson(root: string, file: string, value: unknown): void {
69
+ const target = localPath(root, file);
70
+ const temporary = localPath(root, `${file}.tmp`);
71
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
72
+ renameSync(temporary, target);
73
+ }
74
+
75
+ /** Persist local adapter state with a shared clock and monotonically increasing ids. @public */
76
+ export class LocalProviderStore<
77
+ S extends {
78
+ /** @internal */
79
+ version: number;
80
+ /** @internal */
81
+ sequence: number;
82
+ },
83
+ O extends {
84
+ /** @internal */
85
+ root: string;
86
+ /** @internal */
87
+ now?: () => number;
88
+ /** @internal */
89
+ nextId?: () => number;
90
+ },
91
+ > {
92
+ /** @public */
93
+ readonly git: LocalGit;
94
+ /** @public */
95
+ state: S;
96
+ /** @public */
97
+ constructor(
98
+ /** @public */
99
+ readonly options: O,
100
+ private readonly file: string,
101
+ initial: S,
102
+ ) {
103
+ this.git = new LocalGit(options.root);
104
+ this.state = readLocalJson(options.root, file, initial);
105
+ }
106
+ /** @public */
107
+ save() {
108
+ writeLocalJson(this.options.root, this.file, this.state);
109
+ }
110
+ /** @internal */
111
+ id() {
112
+ this.state.sequence = Math.max(this.state.sequence + 1, this.options.nextId?.() ?? 0);
113
+ return this.state.sequence;
114
+ }
115
+ /** @internal */
116
+ timestamp() {
117
+ return new Date(this.options.now?.() ?? Date.now()).toISOString();
118
+ }
119
+ }
120
+
121
+ /** @public */
122
+ type LocalPullRequest = Pick<
123
+ RepositoryPullRequest,
124
+ "number" | "title" | "body" | "state" | "merged" | "merge_commit_sha" | "head" | "base"
125
+ >;
126
+ /** @public */
127
+ interface LocalPullRequestRepository<P extends LocalPullRequest> {
128
+ /** @public */
129
+ repository: {
130
+ /** @internal */
131
+ ssh_url: string;
132
+ };
133
+ /** @public */
134
+ pulls: P[];
135
+ }
136
+
137
+ /** Common PR operations; adapters retain their provider-specific state and clients. @public */
138
+ export class LocalForgeStore<
139
+ S extends {
140
+ /** @internal */
141
+ version: number;
142
+ /** @internal */
143
+ sequence: number;
144
+ },
145
+ O extends {
146
+ /** @internal */
147
+ root: string;
148
+ /** @internal */
149
+ baseUrl: string;
150
+ /** @internal */
151
+ now?: () => number;
152
+ /** @internal */
153
+ nextId?: () => number;
154
+ },
155
+ > extends LocalProviderStore<S, O> {
156
+ /** @public */
157
+ newRepository(seed: LocalRepositorySeed) {
158
+ const { bare, branch } = this.git.seed(seed);
159
+ return {
160
+ /** @public */
161
+ id: this.id(),
162
+ /** @public */
163
+ owner: {
164
+ /** @internal */
165
+ login: seed.owner,
166
+ },
167
+ /** @public */
168
+ name: seed.name,
169
+ /** @public */
170
+ full_name: `${seed.owner}/${seed.name}`,
171
+ /** @public */
172
+ ssh_url: bare,
173
+ /** @public */
174
+ html_url: `${this.options.baseUrl}/__local`,
175
+ /** @public */
176
+ default_branch: branch,
177
+ };
178
+ }
179
+ /** @internal */
180
+ pullRequestClient<P extends LocalPullRequest>(
181
+ repo: (owner: string, name: string) => LocalPullRequestRepository<P>,
182
+ missing = "Unknown local pull request",
183
+ ) {
184
+ const pull = (owner: string, name: string, number: number) => {
185
+ const pr = repo(owner, name).pulls.find((p) => p.number === number);
186
+ if (!pr) throw new Error(missing);
187
+ return pr;
188
+ };
189
+ return {
190
+ /** @internal */
191
+ getPullRequest: async (owner: string, name: string, number: number) =>
192
+ this.refresh(repo(owner, name), pull(owner, name, number)),
193
+ /** @internal */
194
+ listPullRequests: async (owner: string, name: string, state = "open") => {
195
+ const r = repo(owner, name);
196
+ return r.pulls
197
+ .filter((p) => state === "all" || p.state === state)
198
+ .map((p) => this.refresh(r, p));
199
+ },
200
+ /** @internal */
201
+ updatePullRequest: async (
202
+ owner: string,
203
+ name: string,
204
+ number: number,
205
+ patch: Record<string, unknown>,
206
+ ) => {
207
+ const pr = pull(owner, name, number);
208
+ for (const key of ["title", "body", "state"] as const)
209
+ if (typeof patch[key] === "string") pr[key] = patch[key];
210
+ this.save();
211
+ return this.refresh(repo(owner, name), pr);
212
+ },
213
+ };
214
+ }
215
+ /** @public */
216
+ refresh<P extends LocalPullRequest>(repo: LocalPullRequestRepository<P>, pr: P): P {
217
+ if (pr.state === "open") {
218
+ const { headSha, baseSha, ...mergeability } = this.git.mergeability(
219
+ repo.repository.ssh_url,
220
+ pr.head.ref,
221
+ pr.base.ref,
222
+ );
223
+ pr.head.sha = headSha;
224
+ pr.base.sha = baseSha;
225
+ Object.assign(pr, mergeability);
226
+ }
227
+ return structuredClone(pr);
228
+ }
229
+ /** @public */
230
+ merge<P extends LocalPullRequest>(repo: LocalPullRequestRepository<P>, number: number): P {
231
+ const pr = repo.pulls.find((p) => p.number === number);
232
+ if (!pr || pr.state !== "open") throw new Error("Pull request is not open");
233
+ this.refresh(repo, pr);
234
+ pr.merge_commit_sha = this.git.merge(repo.repository.ssh_url, pr.head.ref, pr.base.ref);
235
+ pr.merged = true;
236
+ pr.state = "closed";
237
+ this.save();
238
+ return structuredClone(pr);
239
+ }
240
+ /** @public */
241
+ addFeedback<F extends RepositoryFeedbackItem>(
242
+ repo: {
243
+ /** @public */
244
+ pulls: Array<{
245
+ /** @internal */
246
+ number: number;
247
+ }>;
248
+ /** @public */
249
+ feedback: Record<string, F[]>;
250
+ },
251
+ number: number,
252
+ input: Omit<F, "id" | "createdAt">,
253
+ ): F {
254
+ if (!repo.pulls.some((p) => p.number === number)) throw new Error("Unknown PR");
255
+ const value = { ...input, id: this.id(), createdAt: this.timestamp() } as F;
256
+ repo.feedback[number] ??= [];
257
+ repo.feedback[number].push(value);
258
+ this.save();
259
+ return value;
260
+ }
261
+ /** @public */
262
+ newComment(body: string) {
263
+ return {
264
+ /** @internal */
265
+ id: this.id(),
266
+ /** @internal */
267
+ body,
268
+ /** @public */
269
+ user: {
270
+ /** @public */
271
+ login: "leitwerk-bot",
272
+ },
273
+ /** @internal */
274
+ created_at: this.timestamp(),
275
+ };
276
+ }
277
+ /** @internal */
278
+ newPullRequest(
279
+ repo: {
280
+ /** @internal */
281
+ repository: {
282
+ /** @internal */
283
+ ssh_url: string;
284
+ };
285
+ },
286
+ input: {
287
+ /** @internal */
288
+ title: string;
289
+ /** @internal */
290
+ body: string;
291
+ /** @internal */
292
+ head: string;
293
+ /** @internal */
294
+ base: string;
295
+ },
296
+ ) {
297
+ const number = this.id();
298
+ return {
299
+ /** @internal */
300
+ number,
301
+ /** @internal */
302
+ title: input.title,
303
+ /** @internal */
304
+ body: input.body,
305
+ /** @internal */
306
+ state: "open",
307
+ /** @internal */
308
+ merged: false,
309
+ /** @internal */
310
+ merge_commit_sha: null,
311
+ /** @internal */
312
+ html_url: `${this.options.baseUrl}/__local#pr-${number}`,
313
+ /** @internal */
314
+ head: {
315
+ /** @internal */
316
+ ref: input.head,
317
+ /** @internal */
318
+ sha: this.git.head(repo.repository.ssh_url, input.head),
319
+ },
320
+ /** @internal */
321
+ base: {
322
+ /** @internal */
323
+ ref: input.base,
324
+ /** @internal */
325
+ sha: this.git.head(repo.repository.ssh_url, input.base),
326
+ },
327
+ };
328
+ }
329
+ }
330
+
331
+ /** Real Git with file-only transport and no ambient credentials or hooks. @public */
332
+ export class LocalGit {
333
+ /** @public */
334
+ constructor(
335
+ /** @internal */
336
+ readonly root: string,
337
+ ) {
338
+ if (lstatSync(root, { throwIfNoEntry: false })?.isSymbolicLink())
339
+ throw new Error("Local Git root must not be a symlink");
340
+ mkdirSync(root, { recursive: true, mode: 0o700 });
341
+ }
342
+ /** @public */
343
+ run(directory: string, args: string[]): string {
344
+ const base = realpathSync(this.root);
345
+ const directoryPath = path.resolve(directory);
346
+ const relative = path.relative(
347
+ directoryPath.startsWith(`${base}${path.sep}`) ? base : path.resolve(this.root),
348
+ directoryPath,
349
+ );
350
+ const cwd = localPath(this.root, relative);
351
+ return traceTestSubprocess(`git ${args[0] ?? ""}`, () =>
352
+ execFileSync(
353
+ "git",
354
+ ["-c", "protocol.file.allow=always", "-c", "core.hooksPath=/dev/null", ...args],
355
+ {
356
+ cwd,
357
+ encoding: "utf8",
358
+ stdio: ["ignore", "pipe", "pipe"],
359
+ env: {
360
+ PATH: process.env.PATH,
361
+ HOME: this.root,
362
+ GIT_CONFIG_NOSYSTEM: "1",
363
+ GIT_CONFIG_GLOBAL: "/dev/null",
364
+ GIT_TERMINAL_PROMPT: "0",
365
+ GIT_ALLOW_PROTOCOL: "file",
366
+ GIT_AUTHOR_NAME: "Sandbox Developer",
367
+ GIT_AUTHOR_EMAIL: "developer@sandbox.invalid",
368
+ GIT_COMMITTER_NAME: "Sandbox Developer",
369
+ GIT_COMMITTER_EMAIL: "developer@sandbox.invalid",
370
+ },
371
+ },
372
+ ).trim(),
373
+ );
374
+ }
375
+ /** @public */
376
+ head(directory: string, ref: string): string {
377
+ if (!/^[a-zA-Z0-9_./-]+$/.test(ref) || ref.startsWith("-")) throw new Error("Invalid Git ref");
378
+ return this.run(directory, ["rev-parse", "--verify", `${ref}^{commit}`]);
379
+ }
380
+ /** @internal */
381
+ isAncestor(directory: string, ancestor: string, descendant: string): boolean {
382
+ return this.isAncestorCommit(
383
+ directory,
384
+ this.head(directory, ancestor),
385
+ this.head(directory, descendant),
386
+ );
387
+ }
388
+ private isAncestorCommit(directory: string, ancestor: string, descendant: string): boolean {
389
+ if (ancestor === descendant) return true;
390
+ try {
391
+ this.run(directory, ["merge-base", "--is-ancestor", ancestor, descendant]);
392
+ return true;
393
+ } catch (error) {
394
+ if ((error as { status?: number }).status === 1) return false;
395
+ throw error;
396
+ }
397
+ }
398
+ /** @internal */
399
+ mergeability(
400
+ directory: string,
401
+ head: string,
402
+ base: string,
403
+ ): {
404
+ /** @internal */
405
+ headSha: string;
406
+ /** @internal */
407
+ baseSha: string;
408
+ /** @internal */
409
+ mergeable: boolean;
410
+ /** @internal */
411
+ mergeable_state: string;
412
+ } {
413
+ const headSha = this.head(directory, head),
414
+ baseSha = this.head(directory, base);
415
+ const revisions = { headSha, baseSha };
416
+ if (this.isAncestorCommit(directory, baseSha, headSha))
417
+ return { ...revisions, mergeable: true, mergeable_state: "clean" };
418
+ try {
419
+ this.run(directory, ["merge-tree", "--write-tree", baseSha, headSha]);
420
+ } catch (error) {
421
+ if ((error as { status?: number }).status === 1)
422
+ return { ...revisions, mergeable: false, mergeable_state: "dirty" };
423
+ throw error;
424
+ }
425
+ return { ...revisions, mergeable: true, mergeable_state: "behind" };
426
+ }
427
+ /** @internal */
428
+ merge(directory: string, head: string, base: string): string {
429
+ const h = this.head(directory, head),
430
+ b = this.head(directory, base);
431
+ let commit = h;
432
+ if (!this.isAncestorCommit(directory, b, h)) {
433
+ const tree = this.run(directory, ["merge-tree", "--write-tree", b, h]).split("\n")[0];
434
+ commit = this.run(directory, [
435
+ "commit-tree",
436
+ tree,
437
+ "-p",
438
+ b,
439
+ "-p",
440
+ h,
441
+ "-m",
442
+ "Merge local pull request",
443
+ ]);
444
+ }
445
+ this.run(directory, ["update-ref", `refs/heads/${base}`, commit, b]);
446
+ return commit;
447
+ }
448
+ /** @internal */
449
+ seed(seed: LocalRepositorySeed): {
450
+ /** @internal */
451
+ bare: string;
452
+ /** @internal */
453
+ worktree: string;
454
+ /** @internal */
455
+ branch: string;
456
+ } {
457
+ for (const value of [seed.owner, seed.name, seed.directoryName ?? seed.name])
458
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(value))
459
+ throw new Error("Invalid local repository name");
460
+ const name = seed.directoryName ?? `${seed.owner}--${seed.name}`;
461
+ const bare = localPath(this.root, `repositories/${name}.git`);
462
+ const worktree = localPath(this.root, `seeds/${name}`);
463
+ const branch = seed.defaultBranch ?? "main";
464
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_./-]*$/.test(branch)) throw new Error("Invalid default branch");
465
+ mkdirSync(bare, { recursive: true });
466
+ mkdirSync(worktree, { recursive: true });
467
+ if (!existsSync(path.join(bare, "HEAD")))
468
+ this.run(bare, ["init", "--bare", `--initial-branch=${branch}`]);
469
+ try {
470
+ this.head(bare, branch);
471
+ return { bare, worktree, branch };
472
+ } catch {
473
+ /* Resume an interrupted seed. */
474
+ }
475
+ if (!existsSync(path.join(worktree, ".git")))
476
+ this.run(worktree, ["init", `--initial-branch=${branch}`]);
477
+ for (const [name, contents] of Object.entries(
478
+ seed.files ?? { "README.md": `# ${seed.name}\n` },
479
+ )) {
480
+ if (name.split(/[\\/]/).includes(".git"))
481
+ throw new Error("Seed must not write Git configuration");
482
+ const target = localPath(worktree, name);
483
+ mkdirSync(path.dirname(target), { recursive: true });
484
+ writeFileSync(target, contents);
485
+ }
486
+ this.run(worktree, ["add", "."]);
487
+ this.run(worktree, [
488
+ "commit",
489
+ "--allow-empty",
490
+ ...(seed.signoff ? ["--signoff"] : []),
491
+ "-m",
492
+ seed.commitMessage ?? "chore: seed local repository",
493
+ ]);
494
+ if (!this.run(worktree, ["remote"]).split("\n").includes("origin"))
495
+ this.run(worktree, ["remote", "add", "origin", bare]);
496
+ this.run(worktree, ["push", bare, `HEAD:refs/heads/${branch}`]);
497
+ return { bare, worktree, branch };
498
+ }
499
+ }
@@ -0,0 +1,36 @@
1
+ import {
2
+ builtinPiProvider,
3
+ defineModelProvider,
4
+ defineModelProviders,
5
+ } from "@leitwerk-dev/process-sdk";
6
+
7
+ /** @public */
8
+ export type FixtureModelProviderSet = ReturnType<typeof defineModelProviders>;
9
+
10
+ /** @public */
11
+ export function fixtureModelProviders(
12
+ ...models: {
13
+ /** @public */
14
+ id: string;
15
+ /** @public */
16
+ modelId: string;
17
+ /** @internal */
18
+ piProvider?: string;
19
+ /** @public */
20
+ server?: boolean;
21
+ }[]
22
+ ): FixtureModelProviderSet {
23
+ return defineModelProviders((rawConfig) =>
24
+ models.map(({ id, modelId, piProvider = id, server = false }) => ({
25
+ definition: defineModelProvider({
26
+ id,
27
+ parseConfig: () => ({ config: {} }),
28
+ worker: builtinPiProvider(piProvider),
29
+ ...(server ? { server: builtinPiProvider(piProvider) } : {}),
30
+ models: () => [{ modelId, availability: "available" }],
31
+ secrets: () => ({}),
32
+ }),
33
+ rawConfig,
34
+ })),
35
+ );
36
+ }
package/src/polling.ts CHANGED
@@ -1,11 +1,12 @@
1
+ /** @public */
1
2
  export async function waitForValue<T>(
2
- read: () => T,
3
+ read: () => T | Promise<T>,
3
4
  predicate: (value: T) => boolean,
4
5
  timeoutMs = 5_000,
5
6
  ): Promise<T> {
6
7
  const deadline = Date.now() + timeoutMs;
7
8
  while (true) {
8
- const value = read();
9
+ const value = await read();
9
10
  if (predicate(value)) {
10
11
  return value;
11
12
  }
@@ -0,0 +1,63 @@
1
+ import type { ProcessInstance } from "@leitwerk-dev/domain";
2
+ import type { AppContext } from "@leitwerk-dev/server";
3
+ import { waitForValue } from "./polling.js";
4
+
5
+ /** Drive a running or restarted app without bypassing process HTTP actions. @public */
6
+ export function createProcessDriver(context: () => AppContext) {
7
+ /** @public */
8
+ async function post(url: string, payload: Record<string, unknown> = {}) {
9
+ const response = await context().app.inject({ method: "POST", url, payload });
10
+ if (response.statusCode !== 200)
11
+ throw new Error(`POST ${url} failed with ${response.statusCode}: ${response.body}`);
12
+ return response;
13
+ }
14
+ /** @public */
15
+ async function waitForProcess(
16
+ id: string,
17
+ predicate: (process: ProcessInstance) => boolean,
18
+ description: string,
19
+ timeout = 12000,
20
+ allowError = false,
21
+ ): Promise<ProcessInstance> {
22
+ try {
23
+ const process = await waitForValue(
24
+ () => {
25
+ const current = context().deps.processes.getById(id);
26
+ if (current?.lifecycleStatus === "error" && !allowError)
27
+ throw new Error("Process entered error lifecycle");
28
+ return current;
29
+ },
30
+ (process) => !!process && predicate(process),
31
+ timeout,
32
+ );
33
+ if (!process) throw new Error("Missing process");
34
+ return process;
35
+ } catch (error) {
36
+ const { processes, turnRecords } = context().deps;
37
+ throw new Error(
38
+ `Waiting for ${id}: ${description}; ${JSON.stringify({ process: processes.getById(id), turns: turnRecords.listByInstance(id) })}`,
39
+ { cause: error },
40
+ );
41
+ }
42
+ }
43
+ return {
44
+ /** @public */
45
+ post,
46
+ /** @public */
47
+ waitForProcess,
48
+ /** @public */
49
+ wait: (id: string, turn: string | null, lifecycle = "waiting", timeout = 12000) =>
50
+ waitForProcess(
51
+ id,
52
+ (p) => p.selectedTurnId === turn && p.lifecycleStatus === lifecycle,
53
+ `${turn}/${lifecycle}`,
54
+ timeout,
55
+ lifecycle === "error",
56
+ ),
57
+ /** @public */
58
+ action: (id: string, action: string, input: Record<string, unknown> = {}) =>
59
+ post(`/api/processes/${encodeURIComponent(id)}/actions/${encodeURIComponent(action)}`, {
60
+ input,
61
+ }),
62
+ };
63
+ }
@@ -1,5 +1,6 @@
1
1
  import type { NormalizedQuestion, ProcessQuestionRequest } from "@leitwerk-dev/domain";
2
2
 
3
+ /** @internal */
3
4
  export function createTestQuestion(
4
5
  overrides: Partial<NormalizedQuestion> = {},
5
6
  ): NormalizedQuestion {
@@ -12,6 +13,7 @@ export function createTestQuestion(
12
13
  };
13
14
  }
14
15
 
16
+ /** @internal */
15
17
  export function createTestQuestionRequest(
16
18
  overrides: Partial<ProcessQuestionRequest> = {},
17
19
  ): ProcessQuestionRequest {