@leitwerk-dev/test-support 0.1.9 → 0.2.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.
- package/dist/{chunk-QFCJV2VA.js → chunk-2IICIB6D.js} +187 -14
- package/dist/chunk-2IICIB6D.js.map +1 -0
- package/dist/{chunk-KIDBCGNW.js → chunk-7I4OCTF3.js} +21 -26
- package/dist/chunk-7I4OCTF3.js.map +1 -0
- package/dist/{chunk-ST2C4VKX.js → chunk-KPSK7EMY.js} +39 -9
- package/dist/chunk-KPSK7EMY.js.map +1 -0
- package/dist/{chunk-R4KVUGWR.js → chunk-MV4W6NOO.js} +25 -3
- package/dist/chunk-MV4W6NOO.js.map +1 -0
- package/dist/compact-process-detail-fixture.d.ts.map +1 -1
- package/dist/fakes/index.js +10 -2
- package/dist/fakes/index.js.map +1 -1
- package/dist/fixtures.js +35 -2
- package/dist/fixtures.js.map +1 -1
- package/dist/http-launch.d.ts +8 -0
- package/dist/http-launch.d.ts.map +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +156 -12
- package/dist/index.js.map +1 -1
- package/dist/integration.d.ts +1 -0
- package/dist/integration.d.ts.map +1 -1
- package/dist/integration.js +66 -4
- package/dist/integration.js.map +1 -1
- package/dist/local-git.d.ts +134 -0
- package/dist/local-git.d.ts.map +1 -0
- package/dist/local-git.js +297 -0
- package/dist/local-git.js.map +1 -0
- package/dist/model-provider-fixtures.d.ts +7 -0
- package/dist/model-provider-fixtures.d.ts.map +1 -0
- package/dist/polling.d.ts +1 -1
- package/dist/polling.d.ts.map +1 -1
- package/dist/process-driver.d.ts +10 -0
- package/dist/process-driver.d.ts.map +1 -0
- package/dist/server-extension-test-harness.d.ts +17 -2
- package/dist/server-extension-test-harness.d.ts.map +1 -1
- package/dist/stub-worker-entry.js +9 -5
- package/dist/stub-worker-entry.js.map +1 -1
- package/dist/worker-testing/in-process-worker-spawn.d.ts +5 -0
- package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -1
- package/dist/worker-testing/index.d.ts +1 -1
- package/dist/worker-testing/index.d.ts.map +1 -1
- package/dist/worker-testing/index.js +371 -7
- package/dist/worker-testing/index.js.map +1 -1
- package/dist/worker-testing/stub-pi-tree-handle.d.ts +19 -1
- package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
- package/dist/worker-testing/worker-start-payload.d.ts.map +1 -1
- package/package.json +14 -9
- package/src/compact-process-detail-fixture.ts +28 -2
- package/src/http-launch.ts +87 -0
- package/src/index.ts +9 -5
- package/src/integration.ts +1 -0
- package/src/local-git.ts +349 -0
- package/src/model-provider-fixtures.ts +23 -0
- package/src/polling.ts +2 -2
- package/src/process-driver.ts +57 -0
- package/src/server-extension-test-harness.ts +42 -5
- package/src/worker-testing/in-process-worker-spawn.ts +22 -2
- package/src/worker-testing/index.ts +5 -1
- package/src/worker-testing/stub-pi-tree-handle.ts +221 -20
- package/src/worker-testing/worker-start-payload.ts +1 -0
- package/dist/chunk-KIDBCGNW.js.map +0 -1
- package/dist/chunk-QFCJV2VA.js.map +0 -1
- package/dist/chunk-R4KVUGWR.js.map +0 -1
- package/dist/chunk-ST2C4VKX.js.map +0 -1
- package/dist/compact-process-detail-fixture.js +0 -73
- package/dist/compact-process-detail-fixture.js.map +0 -1
- package/dist/fakes/fake-git-ops.js +0 -101
- package/dist/fakes/fake-git-ops.js.map +0 -1
- package/dist/fakes/fake-llm.js +0 -27
- package/dist/fakes/fake-llm.js.map +0 -1
- package/dist/in-process-worker.js +0 -2
- package/dist/in-process-worker.js.map +0 -1
- package/dist/integration-harness.js +0 -38
- package/dist/integration-harness.js.map +0 -1
- package/dist/polling.js +0 -14
- package/dist/polling.js.map +0 -1
- package/dist/question-fixtures.js +0 -26
- package/dist/question-fixtures.js.map +0 -1
- package/dist/server-extension-test-harness.js +0 -169
- package/dist/server-extension-test-harness.js.map +0 -1
- package/dist/test-app.js +0 -47
- package/dist/test-app.js.map +0 -1
- package/dist/worker-testing/in-process-worker-spawn.js +0 -61
- package/dist/worker-testing/in-process-worker-spawn.js.map +0 -1
- package/dist/worker-testing/ipc-harness.d.ts +0 -11
- package/dist/worker-testing/ipc-harness.d.ts.map +0 -1
- package/dist/worker-testing/ipc-harness.js +0 -17
- package/dist/worker-testing/ipc-harness.js.map +0 -1
- package/dist/worker-testing/schema-driven-stub-pi.js +0 -65
- package/dist/worker-testing/schema-driven-stub-pi.js.map +0 -1
- package/dist/worker-testing/stub-pi-controls.js +0 -10
- package/dist/worker-testing/stub-pi-controls.js.map +0 -1
- package/dist/worker-testing/stub-pi-tree-handle.js +0 -515
- package/dist/worker-testing/stub-pi-tree-handle.js.map +0 -1
- package/dist/worker-testing/worker-runtime-harness.js +0 -231
- package/dist/worker-testing/worker-runtime-harness.js.map +0 -1
- package/dist/worker-testing/worker-start-payload.js +0 -101
- package/dist/worker-testing/worker-start-payload.js.map +0 -1
- package/dist/workspace-source-aliases.d.ts +0 -6
- package/dist/workspace-source-aliases.d.ts.map +0 -1
- package/dist/workspace-source-aliases.js +0 -126
- package/dist/workspace-source-aliases.js.map +0 -1
- package/src/worker-testing/ipc-harness.ts +0 -19
- package/src/workspace-source-aliases.ts +0 -171
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { LaunchRun } from "@leitwerk-dev/domain";
|
|
2
|
+
|
|
3
|
+
/** Accepts a launch-run request shape and waits for its admitted process commit. */
|
|
4
|
+
export async function postImmediateLaunchRequest(
|
|
5
|
+
input: string | URL | Request,
|
|
6
|
+
init?: RequestInit,
|
|
7
|
+
): Promise<Response> {
|
|
8
|
+
const url = new URL(String(input));
|
|
9
|
+
const match = /^\/api\/launchers\/([^/]+)\/launch-runs$/.exec(url.pathname);
|
|
10
|
+
if (!match?.[1]) throw new Error(`Expected an immediate launch-run URL, received '${url}'`);
|
|
11
|
+
const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
|
|
12
|
+
return postImmediateLaunch(url.origin, decodeURIComponent(match[1]), body);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Admits an immediate launch through the public asynchronous HTTP contract and waits until the
|
|
17
|
+
* process commit or a pre-commit failure is observable. Intended for integration-test setup.
|
|
18
|
+
*/
|
|
19
|
+
export async function postImmediateLaunch(
|
|
20
|
+
serverBaseUrl: string,
|
|
21
|
+
launcherId: string,
|
|
22
|
+
body: Record<string, unknown>,
|
|
23
|
+
): Promise<Response> {
|
|
24
|
+
const admitted = await fetch(
|
|
25
|
+
`${serverBaseUrl.replace(/\/$/, "")}/api/launchers/${encodeURIComponent(launcherId)}/launch-runs`,
|
|
26
|
+
{
|
|
27
|
+
method: "POST",
|
|
28
|
+
headers: { "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
|
|
29
|
+
body: JSON.stringify({ ...body, schedule: { mode: "now" } }),
|
|
30
|
+
},
|
|
31
|
+
);
|
|
32
|
+
const admittedBody = (await admitted.json()) as { launchRunId?: string };
|
|
33
|
+
if (admitted.status !== 202 || !admittedBody.launchRunId) {
|
|
34
|
+
return new Response(JSON.stringify(admittedBody), {
|
|
35
|
+
status: admitted.status,
|
|
36
|
+
headers: { "content-type": "application/json" },
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let launchRun: LaunchRun;
|
|
41
|
+
const deadline = Date.now() + 10_000;
|
|
42
|
+
for (;;) {
|
|
43
|
+
const response = await fetch(
|
|
44
|
+
`${serverBaseUrl.replace(/\/$/, "")}/api/launch-runs/${admittedBody.launchRunId}`,
|
|
45
|
+
);
|
|
46
|
+
const responseBody = (await response.json()) as { launchRun: LaunchRun };
|
|
47
|
+
if (
|
|
48
|
+
responseBody.launchRun.instanceId ||
|
|
49
|
+
["failed", "cancelled"].includes(responseBody.launchRun.status)
|
|
50
|
+
) {
|
|
51
|
+
launchRun = responseBody.launchRun;
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
if (Date.now() >= deadline) throw new Error("Timed out waiting for immediate launch admission");
|
|
55
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!launchRun.instanceId) {
|
|
59
|
+
const failure = launchRun.steps.find((step) => step.status === "failed");
|
|
60
|
+
return new Response(
|
|
61
|
+
JSON.stringify({
|
|
62
|
+
error: failure?.safeSummary ?? "Launch failed",
|
|
63
|
+
launchRunId: launchRun.id,
|
|
64
|
+
}),
|
|
65
|
+
{ status: 400, headers: { "content-type": "application/json" } },
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
const detailResponse = await fetch(
|
|
69
|
+
`${serverBaseUrl.replace(/\/$/, "")}/api/processes/${encodeURIComponent(launchRun.instanceId)}`,
|
|
70
|
+
);
|
|
71
|
+
const detail = (await detailResponse.json()) as { process: unknown; projects?: unknown[] };
|
|
72
|
+
const failure = launchRun.steps.find((step) => step.status === "failed");
|
|
73
|
+
return new Response(
|
|
74
|
+
JSON.stringify({
|
|
75
|
+
process: detail.process,
|
|
76
|
+
projects: detail.projects ?? [],
|
|
77
|
+
launchRunId: launchRun.id,
|
|
78
|
+
...(launchRun.status === "failed"
|
|
79
|
+
? { error: failure?.safeSummary ?? "Process was created, but startup failed" }
|
|
80
|
+
: {}),
|
|
81
|
+
}),
|
|
82
|
+
{
|
|
83
|
+
status: launchRun.status === "failed" ? 200 : 201,
|
|
84
|
+
headers: { "content-type": "application/json" },
|
|
85
|
+
},
|
|
86
|
+
);
|
|
87
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createTestConfigSnapshot as testConfigSnapshot,
|
|
3
|
+
createTestIpcEnvelopeBase as baseEnvelope,
|
|
4
|
+
flushAsyncWork,
|
|
5
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
1
6
|
export { createCompactProcessDetailFixtureFactory } from "./compact-process-detail-fixture.js";
|
|
2
7
|
export { FakeGitOps, type RepoTemplate } from "./fakes/fake-git-ops.js";
|
|
3
8
|
export { FakeLlmProvider, type LlmResponse } from "./fakes/fake-llm.js";
|
|
9
|
+
export { postImmediateLaunch, postImmediateLaunchRequest } from "./http-launch.js";
|
|
4
10
|
export {
|
|
5
11
|
createInProcessWorkerSpawn,
|
|
6
12
|
type InProcessWorkerSpawnOptions,
|
|
@@ -10,20 +16,18 @@ export {
|
|
|
10
16
|
type IntegrationHarness,
|
|
11
17
|
type IntegrationHarnessOptions,
|
|
12
18
|
} from "./integration-harness.js";
|
|
19
|
+
export { fixtureModelProviders } from "./model-provider-fixtures.js";
|
|
13
20
|
export { waitForValue } from "./polling.js";
|
|
14
21
|
export {
|
|
15
22
|
createInMemoryExternalWriteLog,
|
|
23
|
+
createPollingTestExtension,
|
|
16
24
|
createTestServerSetupCapability,
|
|
25
|
+
createToolCollector,
|
|
17
26
|
type InMemoryExternalWriteLog,
|
|
18
27
|
type ServerExtensionTestHarness,
|
|
19
28
|
setupServerExtensionTest,
|
|
20
29
|
} from "./server-extension-test-harness.js";
|
|
21
30
|
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
31
|
export {
|
|
28
32
|
createSchemaDrivenStubPiFactory,
|
|
29
33
|
createSchemaDrivenToolCallScriptResolver,
|
package/src/integration.ts
CHANGED
package/src/local-git.ts
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
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
|
+
|
|
14
|
+
export interface LocalRepositorySeed {
|
|
15
|
+
owner: string;
|
|
16
|
+
name: string;
|
|
17
|
+
defaultBranch?: string;
|
|
18
|
+
files?: Record<string, string>;
|
|
19
|
+
/** Retain a pre-existing sandbox checkout layout. */
|
|
20
|
+
directoryName?: string;
|
|
21
|
+
commitMessage?: string;
|
|
22
|
+
signoff?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Reject escaping paths and symlinks, including a not-yet-created file's parents. */
|
|
26
|
+
export function localPath(root: string, relative: string): string {
|
|
27
|
+
if (lstatSync(root, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
28
|
+
throw new Error("Local provider storage must not contain symlinks");
|
|
29
|
+
const base = realpathSync(root);
|
|
30
|
+
const target = path.resolve(base, relative);
|
|
31
|
+
if (!target.startsWith(`${base}${path.sep}`))
|
|
32
|
+
throw new Error("Path escapes local provider storage");
|
|
33
|
+
let current = base;
|
|
34
|
+
for (const part of path.relative(base, target).split(path.sep)) {
|
|
35
|
+
current = path.join(current, part);
|
|
36
|
+
if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
37
|
+
throw new Error("Local provider storage must not contain symlinks");
|
|
38
|
+
}
|
|
39
|
+
return target;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function readLocalJson<T extends { version: number }>(
|
|
43
|
+
root: string,
|
|
44
|
+
file: string,
|
|
45
|
+
initial: T,
|
|
46
|
+
): T {
|
|
47
|
+
const target = localPath(root, file);
|
|
48
|
+
if (!existsSync(target)) return structuredClone(initial);
|
|
49
|
+
const value = JSON.parse(readFileSync(target, "utf8")) as T;
|
|
50
|
+
if (!value || value.version !== initial.version)
|
|
51
|
+
throw new Error(`Unsupported local state version in ${file}`);
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function writeLocalJson(root: string, file: string, value: unknown): void {
|
|
56
|
+
const target = localPath(root, file);
|
|
57
|
+
const temporary = localPath(root, `${file}.tmp`);
|
|
58
|
+
writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
59
|
+
renameSync(temporary, target);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Persist local adapter state with a shared clock and monotonically increasing ids. */
|
|
63
|
+
export class LocalProviderStore<
|
|
64
|
+
S extends { version: number; sequence: number },
|
|
65
|
+
O extends { root: string; now?: () => number; nextId?: () => number },
|
|
66
|
+
> {
|
|
67
|
+
readonly git: LocalGit;
|
|
68
|
+
state: S;
|
|
69
|
+
constructor(
|
|
70
|
+
readonly options: O,
|
|
71
|
+
private readonly file: string,
|
|
72
|
+
initial: S,
|
|
73
|
+
) {
|
|
74
|
+
this.git = new LocalGit(options.root);
|
|
75
|
+
this.state = readLocalJson(options.root, file, initial);
|
|
76
|
+
}
|
|
77
|
+
save() {
|
|
78
|
+
writeLocalJson(this.options.root, this.file, this.state);
|
|
79
|
+
}
|
|
80
|
+
id() {
|
|
81
|
+
this.state.sequence = Math.max(this.state.sequence + 1, this.options.nextId?.() ?? 0);
|
|
82
|
+
return this.state.sequence;
|
|
83
|
+
}
|
|
84
|
+
timestamp() {
|
|
85
|
+
return new Date(this.options.now?.() ?? Date.now()).toISOString();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
type LocalPullRequest = Pick<
|
|
90
|
+
RepositoryPullRequest,
|
|
91
|
+
"number" | "title" | "body" | "state" | "merged" | "merge_commit_sha" | "head" | "base"
|
|
92
|
+
>;
|
|
93
|
+
interface LocalPullRequestRepository<P extends LocalPullRequest> {
|
|
94
|
+
repository: { ssh_url: string };
|
|
95
|
+
pulls: P[];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Common PR operations; adapters retain their provider-specific state and clients. */
|
|
99
|
+
export class LocalForgeStore<
|
|
100
|
+
S extends { version: number; sequence: number },
|
|
101
|
+
O extends { root: string; baseUrl: string; now?: () => number; nextId?: () => number },
|
|
102
|
+
> extends LocalProviderStore<S, O> {
|
|
103
|
+
newRepository(seed: LocalRepositorySeed) {
|
|
104
|
+
const { bare, branch } = this.git.seed(seed);
|
|
105
|
+
return {
|
|
106
|
+
id: this.id(),
|
|
107
|
+
owner: { login: seed.owner },
|
|
108
|
+
name: seed.name,
|
|
109
|
+
full_name: `${seed.owner}/${seed.name}`,
|
|
110
|
+
ssh_url: bare,
|
|
111
|
+
html_url: `${this.options.baseUrl}/__local`,
|
|
112
|
+
default_branch: branch,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
pullRequestClient<P extends LocalPullRequest>(
|
|
116
|
+
repo: (owner: string, name: string) => LocalPullRequestRepository<P>,
|
|
117
|
+
missing = "Unknown local pull request",
|
|
118
|
+
) {
|
|
119
|
+
const pull = (owner: string, name: string, number: number) => {
|
|
120
|
+
const pr = repo(owner, name).pulls.find((p) => p.number === number);
|
|
121
|
+
if (!pr) throw new Error(missing);
|
|
122
|
+
return pr;
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
getPullRequest: async (owner: string, name: string, number: number) =>
|
|
126
|
+
this.refresh(repo(owner, name), pull(owner, name, number)),
|
|
127
|
+
listPullRequests: async (owner: string, name: string, state = "open") => {
|
|
128
|
+
const r = repo(owner, name);
|
|
129
|
+
return r.pulls
|
|
130
|
+
.filter((p) => state === "all" || p.state === state)
|
|
131
|
+
.map((p) => this.refresh(r, p));
|
|
132
|
+
},
|
|
133
|
+
updatePullRequest: async (
|
|
134
|
+
owner: string,
|
|
135
|
+
name: string,
|
|
136
|
+
number: number,
|
|
137
|
+
patch: Record<string, unknown>,
|
|
138
|
+
) => {
|
|
139
|
+
const pr = pull(owner, name, number);
|
|
140
|
+
for (const key of ["title", "body", "state"] as const)
|
|
141
|
+
if (typeof patch[key] === "string") pr[key] = patch[key];
|
|
142
|
+
this.save();
|
|
143
|
+
return this.refresh(repo(owner, name), pr);
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
refresh<P extends LocalPullRequest>(repo: LocalPullRequestRepository<P>, pr: P): P {
|
|
148
|
+
if (pr.state === "open") {
|
|
149
|
+
const { headSha, baseSha, ...mergeability } = this.git.mergeability(
|
|
150
|
+
repo.repository.ssh_url,
|
|
151
|
+
pr.head.ref,
|
|
152
|
+
pr.base.ref,
|
|
153
|
+
);
|
|
154
|
+
pr.head.sha = headSha;
|
|
155
|
+
pr.base.sha = baseSha;
|
|
156
|
+
Object.assign(pr, mergeability);
|
|
157
|
+
}
|
|
158
|
+
return structuredClone(pr);
|
|
159
|
+
}
|
|
160
|
+
merge<P extends LocalPullRequest>(repo: LocalPullRequestRepository<P>, number: number): P {
|
|
161
|
+
const pr = repo.pulls.find((p) => p.number === number);
|
|
162
|
+
if (!pr || pr.state !== "open") throw new Error("Pull request is not open");
|
|
163
|
+
this.refresh(repo, pr);
|
|
164
|
+
pr.merge_commit_sha = this.git.merge(repo.repository.ssh_url, pr.head.ref, pr.base.ref);
|
|
165
|
+
pr.merged = true;
|
|
166
|
+
pr.state = "closed";
|
|
167
|
+
this.save();
|
|
168
|
+
return structuredClone(pr);
|
|
169
|
+
}
|
|
170
|
+
addFeedback<F extends RepositoryFeedbackItem>(
|
|
171
|
+
repo: { pulls: Array<{ number: number }>; feedback: Record<string, F[]> },
|
|
172
|
+
number: number,
|
|
173
|
+
input: Omit<F, "id" | "createdAt">,
|
|
174
|
+
): F {
|
|
175
|
+
if (!repo.pulls.some((p) => p.number === number)) throw new Error("Unknown PR");
|
|
176
|
+
const value = { ...input, id: this.id(), createdAt: this.timestamp() } as F;
|
|
177
|
+
repo.feedback[number] ??= [];
|
|
178
|
+
repo.feedback[number].push(value);
|
|
179
|
+
this.save();
|
|
180
|
+
return value;
|
|
181
|
+
}
|
|
182
|
+
newComment(body: string) {
|
|
183
|
+
return {
|
|
184
|
+
id: this.id(),
|
|
185
|
+
body,
|
|
186
|
+
user: { login: "leitwerk-bot" },
|
|
187
|
+
created_at: this.timestamp(),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
newPullRequest(
|
|
191
|
+
repo: { repository: { ssh_url: string } },
|
|
192
|
+
input: { title: string; body: string; head: string; base: string },
|
|
193
|
+
) {
|
|
194
|
+
const number = this.id();
|
|
195
|
+
return {
|
|
196
|
+
number,
|
|
197
|
+
title: input.title,
|
|
198
|
+
body: input.body,
|
|
199
|
+
state: "open",
|
|
200
|
+
merged: false,
|
|
201
|
+
merge_commit_sha: null,
|
|
202
|
+
html_url: `${this.options.baseUrl}/__local#pr-${number}`,
|
|
203
|
+
head: { ref: input.head, sha: this.git.head(repo.repository.ssh_url, input.head) },
|
|
204
|
+
base: { ref: input.base, sha: this.git.head(repo.repository.ssh_url, input.base) },
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Real Git with file-only transport and no ambient credentials or hooks. */
|
|
210
|
+
export class LocalGit {
|
|
211
|
+
constructor(readonly root: string) {
|
|
212
|
+
if (lstatSync(root, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
213
|
+
throw new Error("Local Git root must not be a symlink");
|
|
214
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
215
|
+
}
|
|
216
|
+
run(directory: string, args: string[]): string {
|
|
217
|
+
const base = realpathSync(this.root);
|
|
218
|
+
const directoryPath = path.resolve(directory);
|
|
219
|
+
const relative = path.relative(
|
|
220
|
+
directoryPath.startsWith(`${base}${path.sep}`) ? base : path.resolve(this.root),
|
|
221
|
+
directoryPath,
|
|
222
|
+
);
|
|
223
|
+
const cwd = localPath(this.root, relative);
|
|
224
|
+
return execFileSync(
|
|
225
|
+
"git",
|
|
226
|
+
["-c", "protocol.file.allow=always", "-c", "core.hooksPath=/dev/null", ...args],
|
|
227
|
+
{
|
|
228
|
+
cwd,
|
|
229
|
+
encoding: "utf8",
|
|
230
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
231
|
+
env: {
|
|
232
|
+
PATH: process.env.PATH,
|
|
233
|
+
HOME: this.root,
|
|
234
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
235
|
+
GIT_CONFIG_GLOBAL: "/dev/null",
|
|
236
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
237
|
+
GIT_ALLOW_PROTOCOL: "file",
|
|
238
|
+
GIT_AUTHOR_NAME: "Sandbox Developer",
|
|
239
|
+
GIT_AUTHOR_EMAIL: "developer@sandbox.invalid",
|
|
240
|
+
GIT_COMMITTER_NAME: "Sandbox Developer",
|
|
241
|
+
GIT_COMMITTER_EMAIL: "developer@sandbox.invalid",
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
).trim();
|
|
245
|
+
}
|
|
246
|
+
head(directory: string, ref: string): string {
|
|
247
|
+
if (!/^[a-zA-Z0-9_./-]+$/.test(ref) || ref.startsWith("-")) throw new Error("Invalid Git ref");
|
|
248
|
+
return this.run(directory, ["rev-parse", "--verify", `${ref}^{commit}`]);
|
|
249
|
+
}
|
|
250
|
+
isAncestor(directory: string, ancestor: string, descendant: string): boolean {
|
|
251
|
+
return this.isAncestorCommit(
|
|
252
|
+
directory,
|
|
253
|
+
this.head(directory, ancestor),
|
|
254
|
+
this.head(directory, descendant),
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
private isAncestorCommit(directory: string, ancestor: string, descendant: string): boolean {
|
|
258
|
+
if (ancestor === descendant) return true;
|
|
259
|
+
try {
|
|
260
|
+
this.run(directory, ["merge-base", "--is-ancestor", ancestor, descendant]);
|
|
261
|
+
return true;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if ((error as { status?: number }).status === 1) return false;
|
|
264
|
+
throw error;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
mergeability(
|
|
268
|
+
directory: string,
|
|
269
|
+
head: string,
|
|
270
|
+
base: string,
|
|
271
|
+
): { headSha: string; baseSha: string; mergeable: boolean; mergeable_state: string } {
|
|
272
|
+
const headSha = this.head(directory, head),
|
|
273
|
+
baseSha = this.head(directory, base);
|
|
274
|
+
const revisions = { headSha, baseSha };
|
|
275
|
+
if (this.isAncestorCommit(directory, baseSha, headSha))
|
|
276
|
+
return { ...revisions, mergeable: true, mergeable_state: "clean" };
|
|
277
|
+
try {
|
|
278
|
+
this.run(directory, ["merge-tree", "--write-tree", baseSha, headSha]);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if ((error as { status?: number }).status === 1)
|
|
281
|
+
return { ...revisions, mergeable: false, mergeable_state: "dirty" };
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
return { ...revisions, mergeable: true, mergeable_state: "behind" };
|
|
285
|
+
}
|
|
286
|
+
merge(directory: string, head: string, base: string): string {
|
|
287
|
+
const h = this.head(directory, head),
|
|
288
|
+
b = this.head(directory, base);
|
|
289
|
+
let commit = h;
|
|
290
|
+
if (!this.isAncestorCommit(directory, b, h)) {
|
|
291
|
+
const tree = this.run(directory, ["merge-tree", "--write-tree", b, h]).split("\n")[0];
|
|
292
|
+
commit = this.run(directory, [
|
|
293
|
+
"commit-tree",
|
|
294
|
+
tree,
|
|
295
|
+
"-p",
|
|
296
|
+
b,
|
|
297
|
+
"-p",
|
|
298
|
+
h,
|
|
299
|
+
"-m",
|
|
300
|
+
"Merge local pull request",
|
|
301
|
+
]);
|
|
302
|
+
}
|
|
303
|
+
this.run(directory, ["update-ref", `refs/heads/${base}`, commit, b]);
|
|
304
|
+
return commit;
|
|
305
|
+
}
|
|
306
|
+
seed(seed: LocalRepositorySeed): { bare: string; worktree: string; branch: string } {
|
|
307
|
+
for (const value of [seed.owner, seed.name, seed.directoryName ?? seed.name])
|
|
308
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(value))
|
|
309
|
+
throw new Error("Invalid local repository name");
|
|
310
|
+
const name = seed.directoryName ?? `${seed.owner}--${seed.name}`;
|
|
311
|
+
const bare = localPath(this.root, `repositories/${name}.git`);
|
|
312
|
+
const worktree = localPath(this.root, `seeds/${name}`);
|
|
313
|
+
const branch = seed.defaultBranch ?? "main";
|
|
314
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_./-]*$/.test(branch)) throw new Error("Invalid default branch");
|
|
315
|
+
mkdirSync(bare, { recursive: true });
|
|
316
|
+
mkdirSync(worktree, { recursive: true });
|
|
317
|
+
if (!existsSync(path.join(bare, "HEAD")))
|
|
318
|
+
this.run(bare, ["init", "--bare", `--initial-branch=${branch}`]);
|
|
319
|
+
try {
|
|
320
|
+
this.head(bare, branch);
|
|
321
|
+
return { bare, worktree, branch };
|
|
322
|
+
} catch {
|
|
323
|
+
/* Resume an interrupted seed. */
|
|
324
|
+
}
|
|
325
|
+
if (!existsSync(path.join(worktree, ".git")))
|
|
326
|
+
this.run(worktree, ["init", `--initial-branch=${branch}`]);
|
|
327
|
+
for (const [name, contents] of Object.entries(
|
|
328
|
+
seed.files ?? { "README.md": `# ${seed.name}\n` },
|
|
329
|
+
)) {
|
|
330
|
+
if (name.split(/[\\/]/).includes(".git"))
|
|
331
|
+
throw new Error("Seed must not write Git configuration");
|
|
332
|
+
const target = localPath(worktree, name);
|
|
333
|
+
mkdirSync(path.dirname(target), { recursive: true });
|
|
334
|
+
writeFileSync(target, contents);
|
|
335
|
+
}
|
|
336
|
+
this.run(worktree, ["add", "."]);
|
|
337
|
+
this.run(worktree, [
|
|
338
|
+
"commit",
|
|
339
|
+
"--allow-empty",
|
|
340
|
+
...(seed.signoff ? ["--signoff"] : []),
|
|
341
|
+
"-m",
|
|
342
|
+
seed.commitMessage ?? "chore: seed local repository",
|
|
343
|
+
]);
|
|
344
|
+
if (!this.run(worktree, ["remote"]).split("\n").includes("origin"))
|
|
345
|
+
this.run(worktree, ["remote", "add", "origin", bare]);
|
|
346
|
+
this.run(worktree, ["push", bare, `HEAD:refs/heads/${branch}`]);
|
|
347
|
+
return { bare, worktree, branch };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
builtinPiProvider,
|
|
3
|
+
defineModelProvider,
|
|
4
|
+
defineModelProviders,
|
|
5
|
+
} from "@leitwerk-dev/process-sdk";
|
|
6
|
+
|
|
7
|
+
export function fixtureModelProviders(
|
|
8
|
+
...models: { id: string; modelId: string; piProvider?: string; server?: boolean }[]
|
|
9
|
+
) {
|
|
10
|
+
return defineModelProviders((rawConfig) =>
|
|
11
|
+
models.map(({ id, modelId, piProvider = id, server = false }) => ({
|
|
12
|
+
definition: defineModelProvider({
|
|
13
|
+
id,
|
|
14
|
+
parseConfig: () => ({ config: {} }),
|
|
15
|
+
worker: builtinPiProvider(piProvider),
|
|
16
|
+
...(server ? { server: builtinPiProvider(piProvider) } : {}),
|
|
17
|
+
models: () => [{ modelId, availability: "available" }],
|
|
18
|
+
secrets: () => ({}),
|
|
19
|
+
}),
|
|
20
|
+
rawConfig,
|
|
21
|
+
})),
|
|
22
|
+
);
|
|
23
|
+
}
|
package/src/polling.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export async function waitForValue<T>(
|
|
2
|
-
read: () => T
|
|
2
|
+
read: () => T | Promise<T>,
|
|
3
3
|
predicate: (value: T) => boolean,
|
|
4
4
|
timeoutMs = 5_000,
|
|
5
5
|
): Promise<T> {
|
|
6
6
|
const deadline = Date.now() + timeoutMs;
|
|
7
7
|
while (true) {
|
|
8
|
-
const value = read();
|
|
8
|
+
const value = await read();
|
|
9
9
|
if (predicate(value)) {
|
|
10
10
|
return value;
|
|
11
11
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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. */
|
|
6
|
+
export function createProcessDriver(context: () => AppContext) {
|
|
7
|
+
async function post(url: string, payload: Record<string, unknown> = {}) {
|
|
8
|
+
const response = await context().app.inject({ method: "POST", url, payload });
|
|
9
|
+
if (response.statusCode !== 200)
|
|
10
|
+
throw new Error(`POST ${url} failed with ${response.statusCode}: ${response.body}`);
|
|
11
|
+
return response;
|
|
12
|
+
}
|
|
13
|
+
async function waitForProcess(
|
|
14
|
+
id: string,
|
|
15
|
+
predicate: (process: ProcessInstance) => boolean,
|
|
16
|
+
description: string,
|
|
17
|
+
timeout = 12000,
|
|
18
|
+
allowError = false,
|
|
19
|
+
): Promise<ProcessInstance> {
|
|
20
|
+
try {
|
|
21
|
+
const process = await waitForValue(
|
|
22
|
+
() => {
|
|
23
|
+
const current = context().deps.processes.getById(id);
|
|
24
|
+
if (current?.lifecycleStatus === "error" && !allowError)
|
|
25
|
+
throw new Error("Process entered error lifecycle");
|
|
26
|
+
return current;
|
|
27
|
+
},
|
|
28
|
+
(process) => !!process && predicate(process),
|
|
29
|
+
timeout,
|
|
30
|
+
);
|
|
31
|
+
if (!process) throw new Error("Missing process");
|
|
32
|
+
return process;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
const { processes, turnRecords } = context().deps;
|
|
35
|
+
throw new Error(
|
|
36
|
+
`Waiting for ${id}: ${description}; ${JSON.stringify({ process: processes.getById(id), turns: turnRecords.listByInstance(id) })}`,
|
|
37
|
+
{ cause: error },
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
post,
|
|
43
|
+
waitForProcess,
|
|
44
|
+
wait: (id: string, turn: string | null, lifecycle = "waiting", timeout = 12000) =>
|
|
45
|
+
waitForProcess(
|
|
46
|
+
id,
|
|
47
|
+
(p) => p.selectedTurnId === turn && p.lifecycleStatus === lifecycle,
|
|
48
|
+
`${turn}/${lifecycle}`,
|
|
49
|
+
timeout,
|
|
50
|
+
lifecycle === "error",
|
|
51
|
+
),
|
|
52
|
+
action: (id: string, action: string, input: Record<string, unknown> = {}) =>
|
|
53
|
+
post(`/api/processes/${encodeURIComponent(id)}/actions/${encodeURIComponent(action)}`, {
|
|
54
|
+
input,
|
|
55
|
+
}),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -5,15 +5,44 @@ import {
|
|
|
5
5
|
coreHostCapabilities,
|
|
6
6
|
createCapabilityAccessor,
|
|
7
7
|
createEventBus,
|
|
8
|
+
type IntegrationToolDefinition,
|
|
8
9
|
type LeitwerkExtensionModule,
|
|
9
10
|
type ProvidedCapability,
|
|
11
|
+
type ServerExtensionAPI,
|
|
10
12
|
type ServerExtensionEventMap,
|
|
11
13
|
} from "@leitwerk-dev/process-sdk";
|
|
12
|
-
import { flushAsyncWork } from "
|
|
14
|
+
import { flushAsyncWork } from "@leitwerk-dev/worker-protocol";
|
|
13
15
|
|
|
14
16
|
export { flushAsyncWork };
|
|
15
17
|
|
|
18
|
+
/** Register a test provider and expose its poll result without erasing its type. */
|
|
19
|
+
export function createPollingTestExtension<T>(
|
|
20
|
+
manifest: LeitwerkExtensionModule["manifest"],
|
|
21
|
+
setup: (api: ServerExtensionAPI) => { poll(): Promise<T> } | undefined,
|
|
22
|
+
) {
|
|
23
|
+
let provider: ReturnType<typeof setup>;
|
|
24
|
+
return {
|
|
25
|
+
manifest,
|
|
26
|
+
setupServer(api: ServerExtensionAPI) {
|
|
27
|
+
provider = setup(api);
|
|
28
|
+
},
|
|
29
|
+
poll() {
|
|
30
|
+
if (!provider) throw new Error(`Test provider '${manifest.id}' has not been initialized`);
|
|
31
|
+
return provider.poll();
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createToolCollector() {
|
|
37
|
+
const tools = new Map<string, IntegrationToolDefinition>();
|
|
38
|
+
const api = {
|
|
39
|
+
tool: (tool: IntegrationToolDefinition) => tools.set(tool.name, tool),
|
|
40
|
+
} as unknown as ServerExtensionAPI;
|
|
41
|
+
return { api, tools };
|
|
42
|
+
}
|
|
43
|
+
|
|
16
44
|
export interface InMemoryExternalWriteLog {
|
|
45
|
+
records: { dedupKey: string }[];
|
|
17
46
|
hasDedupKey(key: string): boolean;
|
|
18
47
|
record(input: { dedupKey: string }): { dedupKey: string };
|
|
19
48
|
getDedupKeys(): ReadonlySet<string>;
|
|
@@ -21,12 +50,15 @@ export interface InMemoryExternalWriteLog {
|
|
|
21
50
|
|
|
22
51
|
export function createInMemoryExternalWriteLog(): InMemoryExternalWriteLog {
|
|
23
52
|
const dedupKeys = new Set<string>();
|
|
53
|
+
const records: { dedupKey: string }[] = [];
|
|
24
54
|
return {
|
|
55
|
+
records,
|
|
25
56
|
hasDedupKey(key: string) {
|
|
26
57
|
return dedupKeys.has(key);
|
|
27
58
|
},
|
|
28
59
|
record(input: { dedupKey: string }) {
|
|
29
60
|
dedupKeys.add(input.dedupKey);
|
|
61
|
+
records.push(input);
|
|
30
62
|
return input;
|
|
31
63
|
},
|
|
32
64
|
getDedupKeys() {
|
|
@@ -40,6 +72,11 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
40
72
|
serverBaseUrl: "https://leitwerk.example",
|
|
41
73
|
components: {},
|
|
42
74
|
externalWrites: createInMemoryExternalWriteLog(),
|
|
75
|
+
polling: {
|
|
76
|
+
create(options) {
|
|
77
|
+
return { poll: options.pollOnce };
|
|
78
|
+
},
|
|
79
|
+
},
|
|
43
80
|
repositoryCredentials: { register: () => {} },
|
|
44
81
|
processes: {
|
|
45
82
|
create: () => {
|
|
@@ -111,11 +148,11 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
111
148
|
};
|
|
112
149
|
},
|
|
113
150
|
},
|
|
114
|
-
|
|
115
|
-
async
|
|
151
|
+
launchRuns: {
|
|
152
|
+
async startProgrammatic() {
|
|
116
153
|
throw new Error("not used");
|
|
117
154
|
},
|
|
118
|
-
async
|
|
155
|
+
async startWatcher() {
|
|
119
156
|
throw new Error("not used");
|
|
120
157
|
},
|
|
121
158
|
},
|
|
@@ -146,7 +183,7 @@ export function createTestServerSetupCapability(
|
|
|
146
183
|
...overrides.launcherModelConfigs,
|
|
147
184
|
},
|
|
148
185
|
launchPlans: { ...defaults.launchPlans, ...overrides.launchPlans },
|
|
149
|
-
|
|
186
|
+
launchRuns: { ...defaults.launchRuns, ...overrides.launchRuns },
|
|
150
187
|
};
|
|
151
188
|
}
|
|
152
189
|
|