@leitwerk-dev/github-repo-change 0.0.0-bootstrap.0 → 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.
package/src/params.ts ADDED
@@ -0,0 +1,110 @@
1
+ import {
2
+ createRepositoryChangeParamsCodec,
3
+ normalizeRepositoryChangeParamsInput,
4
+ type RepositoryChangeLaunchParams,
5
+ repositoryChangeParamsRecord,
6
+ } from "@leitwerk-dev/coding/repository-change-launch";
7
+ import { trimString } from "@leitwerk-dev/domain";
8
+
9
+ /** @public */
10
+ interface GitHubRepoChangeCommonParams {
11
+ /** @public */
12
+ githubProfile: string;
13
+ /** @public */
14
+ sshCredentialRef: string;
15
+ /** @public */
16
+ owner: string;
17
+ /** @public */
18
+ repo: string;
19
+ }
20
+
21
+ /** @public */
22
+ export interface GitHubIssueOriginParams {
23
+ /** @public */
24
+ origin: "issue";
25
+ /** @public */
26
+ issueNumber: number;
27
+ /** @public */
28
+ issueUrl: string;
29
+ /** @public */
30
+ triggerLabel: string;
31
+ /** @public */
32
+ doneLabel: string;
33
+ }
34
+
35
+ /** @public */
36
+ export interface GitHubUiOriginParams {
37
+ /** @public */
38
+ origin: "ui";
39
+ /** @public */
40
+ issueNumber: null;
41
+ /** @public */
42
+ issueUrl: null;
43
+ /** @public */
44
+ triggerLabel: null;
45
+ /** @public */
46
+ doneLabel: null;
47
+ }
48
+
49
+ /** @public */
50
+ export type GitHubRepoChangeParams = RepositoryChangeLaunchParams<
51
+ GitHubRepoChangeCommonParams & (GitHubIssueOriginParams | GitHubUiOriginParams)
52
+ >;
53
+
54
+ /** @public */
55
+ export function isIssueOrigin(
56
+ params: GitHubRepoChangeParams,
57
+ ): params is GitHubRepoChangeParams & GitHubIssueOriginParams {
58
+ return params.origin === "issue";
59
+ }
60
+
61
+ /** @public */
62
+ export const githubRepoChangeParamsCodec =
63
+ createRepositoryChangeParamsCodec<GitHubRepoChangeParams>({
64
+ normalize(value) {
65
+ const shared = normalizeRepositoryChangeParamsInput(value, "GitHub Repo Change");
66
+ const record = repositoryChangeParamsRecord(value, "GitHub Repo Change");
67
+ const text = (name: string) => {
68
+ const value = trimString(record[name]);
69
+ if (!value) throw new Error(`GitHub Repo Change requires ${name}`);
70
+ return value;
71
+ };
72
+
73
+ const common = {
74
+ ...shared,
75
+ githubProfile: text("githubProfile"),
76
+ sshCredentialRef: text("sshCredentialRef"),
77
+ owner: text("owner"),
78
+ repo: text("repo"),
79
+ };
80
+ const origin = trimString(record.origin);
81
+ if (origin === "ui") {
82
+ return {
83
+ ...common,
84
+ origin: "ui" as const,
85
+ issueNumber: null,
86
+ issueUrl: null,
87
+ triggerLabel: null,
88
+ doneLabel: null,
89
+ };
90
+ }
91
+ if (origin && origin !== "issue") {
92
+ throw new Error("GitHub Repo Change requires a valid origin");
93
+ }
94
+
95
+ if (
96
+ typeof record.issueNumber !== "number" ||
97
+ !Number.isInteger(record.issueNumber) ||
98
+ record.issueNumber <= 0
99
+ )
100
+ throw new Error("GitHub Repo Change requires issueNumber");
101
+ return {
102
+ ...common,
103
+ origin: "issue" as const,
104
+ issueNumber: record.issueNumber,
105
+ issueUrl: text("issueUrl"),
106
+ triggerLabel: text("triggerLabel"),
107
+ doneLabel: text("doneLabel"),
108
+ };
109
+ },
110
+ });
package/src/process.ts ADDED
@@ -0,0 +1,391 @@
1
+ import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
2
+ import {
3
+ createRepositoryChangePublication,
4
+ publicationObject as object,
5
+ type PublicationContext,
6
+ type PublicationSource,
7
+ type PublicationState,
8
+ readPublicationState,
9
+ } from "@leitwerk-dev/coding/repository-change-publication";
10
+ import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
11
+ import {
12
+ type GitHubGitIdentity,
13
+ type GitHubPullRequest,
14
+ githubExternal,
15
+ githubIssueWatcherSource,
16
+ } from "@leitwerk-dev/github";
17
+ import type { FlowAutomaticRunContext } from "@leitwerk-dev/process-sdk";
18
+ import {
19
+ type createGitHubRepoChangeLauncher,
20
+ githubRepoChangeLaunchConfig,
21
+ githubRepoChangeParams,
22
+ } from "./launcher.js";
23
+ import {
24
+ type GitHubIssueOriginParams,
25
+ type GitHubRepoChangeParams,
26
+ githubRepoChangeParamsCodec,
27
+ isIssueOrigin,
28
+ } from "./params.js";
29
+
30
+ const processId = "github_repo_change_process";
31
+ const ids = {
32
+ deliver: "deliver_change",
33
+ feedback: "revise_from_pull_request_feedback",
34
+ ciRepair: "repair_github_checks",
35
+ operator: "ci_operator_action",
36
+ };
37
+ const remote = (state: RepositoryChangeState) => readPublicationState(state, "githubRepoChange");
38
+ function requirePr(state: RepositoryChangeState) {
39
+ const value = remote(state);
40
+ if (!value.headSha || !value.prNumber || !value.prUrl)
41
+ throw new Error("Pull request delivery state is incomplete");
42
+ return { ...value, headSha: value.headSha, prNumber: value.prNumber, prUrl: value.prUrl };
43
+ }
44
+ const feedbackKey = (value: { kind: string; id: number }) => `${value.kind}:${value.id}`;
45
+ const callFor =
46
+ (ctx: PublicationContext<GitHubRepoChangeParams>) =>
47
+ <T>(name: string, args: Record<string, unknown>) =>
48
+ ctx.callIntegrationTool(name, { projectKey: "repo", ...args }) as Promise<T>;
49
+ function requireIssueOrigin(
50
+ params: GitHubRepoChangeParams,
51
+ ): GitHubRepoChangeParams & GitHubIssueOriginParams {
52
+ if (!isIssueOrigin(params)) throw new Error("GitHub source issue metadata is unavailable");
53
+ return params;
54
+ }
55
+
56
+ function pinnedGitIdentity(
57
+ ctx: FlowAutomaticRunContext<GitHubRepoChangeParams, RepositoryChangeState>,
58
+ ): GitHubGitIdentity | null {
59
+ const project = ctx.projects.find((candidate) => candidate.key === "repo");
60
+ const candidate = object(project?.metadata)?.["leitwerk.gitIdentity"];
61
+ const identity = object(candidate);
62
+ if (
63
+ identity.provider !== "github" ||
64
+ identity.profile !== ctx.params.githubProfile ||
65
+ typeof identity.login !== "string" ||
66
+ !identity.login.trim() ||
67
+ typeof identity.name !== "string" ||
68
+ !identity.name.trim() ||
69
+ typeof identity.email !== "string" ||
70
+ !identity.email.trim()
71
+ ) {
72
+ return null;
73
+ }
74
+ return identity as unknown as GitHubGitIdentity;
75
+ }
76
+
77
+ const deliveryTools = [
78
+ "github_get_pull_request",
79
+ "github_add_pull_request_comment",
80
+ "github_resolve_git_identity",
81
+ "github_ensure_pull_request",
82
+ "github_add_issue_comment",
83
+ "github_add_pull_request_feedback_reaction",
84
+ "github_reply_to_pull_request_feedback",
85
+ "github_get_issue",
86
+ "github_ensure_label",
87
+ "github_update_issue",
88
+ ] as const;
89
+
90
+ /** @public */
91
+ export function createGitHubRepoChangeProcess(
92
+ launcher: ReturnType<typeof createGitHubRepoChangeLauncher>,
93
+ docker: boolean,
94
+ ) {
95
+ const failedPipeline = githubExternal.checks<GitHubRepoChangeParams, RepositoryChangeState>(
96
+ ({ params, state }) => ({
97
+ profile: params.githubProfile,
98
+ owner: params.owner,
99
+ repo: params.repo,
100
+ prNumber: requirePr(state).prNumber,
101
+ headSha: requirePr(state).headSha,
102
+ afterKey: remote(state).pipeline?.evidenceKey as string | undefined,
103
+ }),
104
+ );
105
+
106
+ const sources: PublicationSource<GitHubRepoChangeParams>[] = [
107
+ {
108
+ id: "github_merge_conflict",
109
+ kind: "conflict",
110
+ label: "Rebase conflicting pull request",
111
+ source: githubExternal.pullRequestState(({ params, state }) => ({
112
+ profile: params.githubProfile,
113
+ owner: params.owner,
114
+ repo: params.repo,
115
+ prNumber: requirePr(state).prNumber,
116
+ headSha: requirePr(state).headSha,
117
+ lastConflictKey: remote(state).lastConflictKey,
118
+ feedbackCursor: 0,
119
+ eventKinds: ["merge_conflict"],
120
+ pollInterval: "30s",
121
+ })),
122
+ read: ({ event }) => ({
123
+ kind: "conflict",
124
+ conflict: object(event).conflict as NonNullable<PublicationState["conflict"]>,
125
+ }),
126
+ },
127
+ {
128
+ id: "github_feedback",
129
+ kind: "feedback",
130
+ label: "GitHub pull request feedback",
131
+ source: githubExternal.pullRequestFeedback(({ params, state }) => ({
132
+ profile: params.githubProfile,
133
+ owner: params.owner,
134
+ repo: params.repo,
135
+ prNumber: requirePr(state).prNumber,
136
+ conversationCursor: remote(state).conversationCursor,
137
+ reviewCursor: remote(state).reviewCursor,
138
+ inlineCursor: remote(state).inlineCursor,
139
+ quietPeriodMs: 120000,
140
+ pollInterval: "30s",
141
+ })),
142
+ read: ({ state, event }) => {
143
+ const value = object(event);
144
+ const cursors = object(value.cursors);
145
+ const current = remote(state);
146
+ return {
147
+ kind: "feedback",
148
+ conversationCursor: Number(cursors.conversationCursor ?? current.conversationCursor),
149
+ reviewCursor: Number(cursors.reviewCursor ?? current.reviewCursor),
150
+ inlineCursor: Number(cursors.inlineCursor ?? current.inlineCursor),
151
+ feedbackIds: (value.feedbackIds ?? []) as PublicationState["feedbackIds"],
152
+ };
153
+ },
154
+ },
155
+ {
156
+ id: "github_failure_repair",
157
+ operatorId: "github_failure_operator",
158
+ kind: "failure",
159
+ label: "Repair failed GitHub checks",
160
+ source: failedPipeline,
161
+ read: ({ state, event }) => {
162
+ const checks = object(object(event).checks);
163
+ const current = requirePr(state);
164
+ if (checks.headSha !== current.headSha) throw new Error("Stale GitHub check evidence");
165
+ const failed = Array.isArray(checks.failed) ? checks.failed : [];
166
+ return {
167
+ kind: "failure",
168
+ pipeline: {
169
+ number: 0,
170
+ status: "failure",
171
+ ...checks,
172
+ evidenceKey: `${checks.headSha}:${failed.map((run) => object(run).url).join(":")}`,
173
+ },
174
+ };
175
+ },
176
+ },
177
+ ...(["merged", "closed"] as const).map((terminalOutcome) => ({
178
+ id: `github_pr_${terminalOutcome}`,
179
+ kind: "terminal" as const,
180
+ label: `GitHub pull request ${terminalOutcome}`,
181
+ source: githubExternal.pullRequestTerminal<GitHubRepoChangeParams, RepositoryChangeState>(
182
+ ({ params, state }) => ({
183
+ profile: params.githubProfile,
184
+ owner: params.owner,
185
+ repo: params.repo,
186
+ prNumber: requirePr(state).prNumber,
187
+ terminalOutcome,
188
+ pollInterval: "30s",
189
+ }),
190
+ ),
191
+ read: ({ event }: { event: unknown }) => ({
192
+ kind: "terminal" as const,
193
+ request: object(event).pullRequest as GitHubPullRequest,
194
+ }),
195
+ })),
196
+ {
197
+ id: "source_cancelled",
198
+ kind: "cancelled",
199
+ label: "Source issue cancelled",
200
+ enabled: isIssueOrigin,
201
+ source: githubExternal.issueCancelled(({ params }) => {
202
+ const issue = requireIssueOrigin(params);
203
+ return {
204
+ profile: issue.githubProfile,
205
+ owner: issue.owner,
206
+ repo: issue.repo,
207
+ issueNumber: issue.issueNumber,
208
+ triggerLabel: issue.triggerLabel,
209
+ pollInterval: "30s",
210
+ };
211
+ }),
212
+ read: () => ({ kind: "cancelled" }),
213
+ },
214
+ ];
215
+ const publicationConfig = createRepositoryChangePublication<GitHubRepoChangeParams>({
216
+ namespace: "githubRepoChange",
217
+ label: "GitHub PR",
218
+ ids,
219
+ sources,
220
+ tools: {
221
+ delivery: deliveryTools,
222
+ feedback: ["github_get_pull_request", "github_list_pull_request_feedback"],
223
+ ci: ["github_get_ci_diagnostics"],
224
+ },
225
+ async identity(ctx) {
226
+ return (
227
+ pinnedGitIdentity(ctx) ??
228
+ (await callFor(ctx)<GitHubGitIdentity>("github_resolve_git_identity", {}))
229
+ );
230
+ },
231
+ async reconcileTerminal(ctx, _current, pr) {
232
+ const call = callFor(ctx);
233
+ if (isIssueOrigin(ctx.params)) {
234
+ const issue = await call<{
235
+ labels: Array<{ name: string }>;
236
+ }>("github_get_issue", {
237
+ issueNumber: ctx.params.issueNumber,
238
+ });
239
+ let labels = issue.labels
240
+ .filter((label) => label.name !== ctx.params.triggerLabel)
241
+ .map((label) => label.name);
242
+ if (pr.merged) {
243
+ const done = await call<{ name: string }>("github_ensure_label", {
244
+ name: ctx.params.doneLabel,
245
+ });
246
+ labels = [...new Set([...labels, done.name])];
247
+ }
248
+ await call("github_update_issue", {
249
+ issueNumber: ctx.params.issueNumber,
250
+ patch: { labels, ...(pr.merged ? { state: "closed" } : {}) },
251
+ writeKey: `github:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`,
252
+ });
253
+ await call("github_add_issue_comment", {
254
+ issueNumber: ctx.params.issueNumber,
255
+ body: pr.merged
256
+ ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.`
257
+ : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
258
+ writeKey: `github:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`,
259
+ });
260
+ }
261
+ },
262
+ async ensureRequest(ctx) {
263
+ const call = callFor(ctx);
264
+ const project = ctx.repo.get("repo");
265
+ const issueOrigin = isIssueOrigin(ctx.params);
266
+ const pr = await call<GitHubPullRequest>("github_ensure_pull_request", {
267
+ title:
268
+ ctx.process.title ??
269
+ (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
270
+ body: issueOrigin
271
+ ? `Implements ${ctx.params.issueUrl}\n\nLeitwerk process: ${ctx.process.id}`
272
+ : `Leitwerk process: ${ctx.process.id}`,
273
+ head: project.workBranch,
274
+ base: project.baseBranch,
275
+ });
276
+ if (!pr) throw new Error("GitHub pull request could not be created or found");
277
+ return pr;
278
+ },
279
+ async linkIssue(ctx, current) {
280
+ const call = callFor(ctx);
281
+ if (isIssueOrigin(ctx.params)) {
282
+ await call("github_add_issue_comment", {
283
+ issueNumber: ctx.params.issueNumber,
284
+ body: `Leitwerk opened pull request ${current.prUrl}.`,
285
+ writeKey: `github:${ctx.process.id}:source-pr-link:${current.prNumber}`,
286
+ });
287
+ }
288
+ },
289
+ async reply(ctx, current) {
290
+ const call = callFor(ctx);
291
+ for (const feedback of current.feedbackIds) {
292
+ await call("github_reply_to_pull_request_feedback", {
293
+ pullRequestNumber: current.prNumber,
294
+ feedbackKind: feedback.kind,
295
+ feedbackId: feedback.id,
296
+ body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
297
+ writeKey: `github:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`,
298
+ });
299
+ }
300
+ },
301
+ async acknowledge(ctx, current) {
302
+ const call = callFor(ctx);
303
+ for (const feedback of current.feedbackIds) {
304
+ if (feedback.kind === "review") continue;
305
+ await call("github_add_pull_request_feedback_reaction", {
306
+ pullRequestNumber: current.prNumber,
307
+ feedbackKind: feedback.kind,
308
+ feedbackId: feedback.id,
309
+ writeKey: `github:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`,
310
+ });
311
+ }
312
+ },
313
+ async head(ctx, current) {
314
+ return (
315
+ await callFor(ctx)<GitHubPullRequest>("github_get_pull_request", {
316
+ pullRequestNumber: current.prNumber,
317
+ })
318
+ ).head.sha;
319
+ },
320
+ async afterRebase(ctx, current) {
321
+ await callFor(ctx)("github_add_pull_request_comment", {
322
+ pullRequestNumber: current.prNumber,
323
+ body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
324
+ writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`,
325
+ });
326
+ },
327
+ commitMessage: (kind) =>
328
+ kind === "feedback" ? "fix: address GitHub review feedback" : "fix: repair GitHub checks",
329
+ prompt(kind, current) {
330
+ return kind === "feedback"
331
+ ? `Address the unseen GitHub pull-request feedback batch for PR #${current.prNumber}. Feedback identifiers: ${JSON.stringify(current.feedbackIds)}. Inspect the current checkout and use GitHub tools to read the full feedback. Do not rely on an earlier plan or conversation. Make only justified repository changes. Call changes_ready if files need publishing, no_changes after an explicit diagnosis that no repository change is needed, or cannot_repair when operator action is required.`
332
+ : `Diagnose failed GitHub checks for request #${current.prNumber}, head ${current.headSha}. Use github_get_ci_diagnostics with pullRequestNumber and headSha to inspect failed check annotations and bounded Actions job logs before changing anything. Fix repository causes. Call changes_ready for repository changes, no_changes only after an explicit provider restart or a justified diagnosis that no repository change is needed, or cannot_repair when operator action is required.`;
333
+ },
334
+ });
335
+ const publication = publicationConfig.fragment;
336
+ publication.watcher({
337
+ id: "use_leitwerk",
338
+ label: "GitHub use-leitwerk issues",
339
+ description: "Launch a remote repository change for GitHub issues carrying the trigger label",
340
+ source: githubIssueWatcherSource,
341
+ preparationChecks: launcher.preparationChecks,
342
+ async resolveLaunchConfig({ profile, repository, issue, labels }) {
343
+ const issueNumber = issue.number;
344
+ const title = issue.title.trim();
345
+ const body = issue.body?.trim() ?? "";
346
+ const issueUrl = issue.html_url;
347
+ const binding = launcher.resolveProfiles(profile);
348
+ const gitIdentity = await launcher.resolveGitIdentity(profile);
349
+ const params: GitHubRepoChangeParams = {
350
+ ...githubRepoChangeParams(repository, {
351
+ ...binding,
352
+ profile,
353
+ workBranch: `leitwerk/issue-${issueNumber}`,
354
+ prompt: `${title}${body ? `\n\n${body}` : ""}`,
355
+ }),
356
+ origin: "issue",
357
+ issueNumber,
358
+ issueUrl,
359
+ triggerLabel: labels.trigger,
360
+ doneLabel: labels.done,
361
+ };
362
+ return githubRepoChangeLaunchConfig(params, title, gitIdentity);
363
+ },
364
+ });
365
+
366
+ const definition = createRepositoryChangeProcess<GitHubRepoChangeParams>({
367
+ processId,
368
+ displayName: "GitHub Repo Change",
369
+ paramsCodec: githubRepoChangeParamsCodec,
370
+ launcher: launcher.launcher,
371
+ finalizeLabel: "Publish pull request",
372
+ finalizeForm: {
373
+ id: "github_publish",
374
+ title: "Publish pull request",
375
+ fields: [],
376
+ submitLabel: "Publish",
377
+ },
378
+ repositoryCredentials: ({ params }) => [
379
+ {
380
+ projectKey: "repo",
381
+ kind: "git_ssh",
382
+ credentialRef: params.sshCredentialRef,
383
+ },
384
+ ],
385
+ publication: publicationConfig,
386
+ });
387
+
388
+ definition.process.runtime = { ...definition.process.runtime, docker };
389
+
390
+ return definition.process;
391
+ }
@@ -0,0 +1,53 @@
1
+ /** Server-owned, non-secret wiring for future launches. */
2
+ /** @public */
3
+ export interface ProfileBinding {
4
+ /** @public */
5
+ sshCredentialRef: string;
6
+ }
7
+ /** @public */
8
+ export type ProfileBindings = Readonly<Record<string, Readonly<ProfileBinding>>>;
9
+
10
+ function record(value: unknown, label: string): Record<string, unknown> {
11
+ if (!value || typeof value !== "object" || Array.isArray(value))
12
+ throw new Error(`${label} must be an object`);
13
+ return value as Record<string, unknown>;
14
+ }
15
+ function field(value: unknown, fallback: string, label: string): string {
16
+ if (value === undefined) return fallback;
17
+ if (typeof value !== "string" || !value.trim())
18
+ throw new Error(`${label} must be a non-empty string`);
19
+ return value.trim();
20
+ }
21
+ /** @public */
22
+ export function parseProfileBindings(raw: unknown): ProfileBindings {
23
+ const config = raw === undefined ? {} : record(raw, "github-repo-change configuration");
24
+ if (config.profile_bindings === undefined) return Object.freeze({});
25
+ const mappings = record(config.profile_bindings, "profile_bindings");
26
+ const entries = Object.entries(mappings).map(([profile, value]) => {
27
+ if (!profile.trim() || profile.trim() !== profile)
28
+ throw new Error(
29
+ "profile_bindings keys must be non-empty profile names without surrounding whitespace",
30
+ );
31
+ const mapping = record(value, `profile_bindings.${profile}`);
32
+ for (const key of Object.keys(mapping))
33
+ if (key !== "ssh_credential_ref")
34
+ throw new Error(`Unknown profile_bindings.${profile}.${key}`);
35
+ return [
36
+ profile,
37
+ Object.freeze({
38
+ sshCredentialRef: field(
39
+ mapping.ssh_credential_ref,
40
+ profile,
41
+ `profile_bindings.${profile}.ssh_credential_ref`,
42
+ ),
43
+ }),
44
+ ];
45
+ });
46
+ return Object.freeze(Object.fromEntries(entries));
47
+ }
48
+ /** @public */
49
+ export function resolveProfileBinding(bindings: ProfileBindings, profile: string): ProfileBinding {
50
+ return Object.hasOwn(bindings, profile)
51
+ ? { ...bindings[profile] }
52
+ : { sshCredentialRef: profile };
53
+ }