@leitwerk-dev/github-repo-change 0.3.0 → 0.3.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.
package/src/process.ts CHANGED
@@ -2,26 +2,18 @@ import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
2
2
  import {
3
3
  createRepositoryChangePublication,
4
4
  publicationObject as object,
5
- type PublicationContext,
6
5
  type PublicationSource,
7
6
  type PublicationState,
7
+ pullRequestPublicationCallbacks,
8
+ pullRequestPublicationSources,
8
9
  readPublicationState,
10
+ reconcilePullRequestSourceIssue,
11
+ resolvePullRequestGitIdentity,
9
12
  } from "@leitwerk-dev/coding/repository-change-publication";
10
13
  import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
14
+ import { githubExternal, githubIssueWatcherSource } from "@leitwerk-dev/github";
15
+ import type { createGitHubRepoChangeLauncher } from "./launcher.js";
11
16
  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
17
  type GitHubRepoChangeParams,
26
18
  githubRepoChangeParamsCodec,
27
19
  isIssueOrigin,
@@ -35,44 +27,6 @@ const ids = {
35
27
  operator: "ci_operator_action",
36
28
  };
37
29
  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
30
 
77
31
  const deliveryTools = [
78
32
  "github_get_pull_request",
@@ -92,6 +46,14 @@ export function createGitHubRepoChangeProcess(
92
46
  launcher: ReturnType<typeof createGitHubRepoChangeLauncher>,
93
47
  docker: boolean,
94
48
  ) {
49
+ const sharedSources = pullRequestPublicationSources<GitHubRepoChangeParams>(
50
+ "github",
51
+ "GitHub",
52
+ githubExternal,
53
+ (params) => params.githubProfile,
54
+ (params) => (isIssueOrigin(params) ? params : undefined),
55
+ );
56
+ const { requirePr } = sharedSources;
95
57
  const failedPipeline = githubExternal.checks<GitHubRepoChangeParams, RepositoryChangeState>(
96
58
  ({ params, state }) => ({
97
59
  profile: params.githubProfile,
@@ -124,34 +86,7 @@ export function createGitHubRepoChangeProcess(
124
86
  conflict: object(event).conflict as NonNullable<PublicationState["conflict"]>,
125
87
  }),
126
88
  },
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
- },
89
+ sharedSources.feedback,
155
90
  {
156
91
  id: "github_failure_repair",
157
92
  operatorId: "github_failure_operator",
@@ -174,43 +109,8 @@ export function createGitHubRepoChangeProcess(
174
109
  };
175
110
  },
176
111
  },
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
- },
112
+ ...sharedSources.terminal,
113
+ sharedSources.cancelled,
214
114
  ];
215
115
  const publicationConfig = createRepositoryChangePublication<GitHubRepoChangeParams>({
216
116
  namespace: "githubRepoChange",
@@ -222,108 +122,15 @@ export function createGitHubRepoChangeProcess(
222
122
  feedback: ["github_get_pull_request", "github_list_pull_request_feedback"],
223
123
  ci: ["github_get_ci_diagnostics"],
224
124
  },
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
- },
125
+ identity: (ctx) => resolvePullRequestGitIdentity(ctx, "github", ctx.params.githubProfile),
126
+ reconcileTerminal: reconcilePullRequestSourceIssue<GitHubRepoChangeParams>(
127
+ "github",
128
+ "name",
129
+ (params) => (isIssueOrigin(params) ? params : undefined),
130
+ ),
131
+ ...pullRequestPublicationCallbacks<GitHubRepoChangeParams>("github", "GitHub", (params) =>
132
+ isIssueOrigin(params) ? params : undefined,
133
+ ),
327
134
  commitMessage: (kind) =>
328
135
  kind === "feedback" ? "fix: address GitHub review feedback" : "fix: repair GitHub checks",
329
136
  prompt(kind, current) {
@@ -339,28 +146,7 @@ export function createGitHubRepoChangeProcess(
339
146
  description: "Launch a remote repository change for GitHub issues carrying the trigger label",
340
147
  source: githubIssueWatcherSource,
341
148
  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
- },
149
+ resolveLaunchConfig: launcher.launcher.resolveIssueLaunchConfig,
364
150
  });
365
151
 
366
152
  const definition = createRepositoryChangeProcess<GitHubRepoChangeParams>({
@@ -1,3 +1,5 @@
1
+ import { parseRepositoryProfileBindings } from "@leitwerk-dev/coding/repository-change-launch";
2
+
1
3
  /** Server-owned, non-secret wiring for future launches. */
2
4
  /** @public */
3
5
  export interface ProfileBinding {
@@ -7,43 +9,11 @@ export interface ProfileBinding {
7
9
  /** @public */
8
10
  export type ProfileBindings = Readonly<Record<string, Readonly<ProfileBinding>>>;
9
11
 
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
12
  /** @public */
22
13
  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
- ];
14
+ return parseRepositoryProfileBindings(raw, "github-repo-change", {
15
+ sshCredentialRef: "ssh_credential_ref",
45
16
  });
46
- return Object.freeze(Object.fromEntries(entries));
47
17
  }
48
18
  /** @public */
49
19
  export function resolveProfileBinding(bindings: ProfileBindings, profile: string): ProfileBinding {