@leitwerk-dev/gitlab-repo-change 0.3.0 → 0.4.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/process.ts CHANGED
@@ -1,110 +1,67 @@
1
1
  import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
2
+ import type { RepositoryChangePublicationAdapter } from "@leitwerk-dev/coding/repository-change-publication";
2
3
  import {
3
4
  createRepositoryChangePublication,
4
- publicationObject as object,
5
- type PublicationContext,
6
5
  type PublicationEvidence,
7
- type PublicationRequest,
8
6
  type PublicationSource,
9
7
  readPublicationState,
10
8
  } from "@leitwerk-dev/coding/repository-change-publication";
11
9
  import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
12
10
  import {
11
+ createGitLabPublicationAdapter,
13
12
  type GitLabDeliveryObservation,
14
- type GitLabMergeRequest,
15
13
  gitlabExternal,
16
14
  gitlabIssueWatcherSource,
17
- gitlabRepositoryCredentials,
15
+ gitlabPublicationEvidenceForRequest,
18
16
  } from "@leitwerk-dev/gitlab";
17
+ import type { ExtensionProcessDefinition, ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
19
18
  import type { createGitLabRepoChangeLauncher } from "./launcher.js";
20
19
  import { type GitLabRepoChangeParams, gitlabRepoChangeParamsCodec } from "./params.js";
21
20
 
22
21
  const remote = (state: RepositoryChangeState) => readPublicationState(state, "gitlabRepoChange");
23
- const request = (mr: GitLabMergeRequest): PublicationRequest => ({
24
- number: mr.iid,
25
- html_url: mr.web_url,
26
- merged: mr.state === "merged",
27
- merge_commit_sha: mr.merge_commit_sha,
28
- });
29
- const callFor =
30
- (ctx: PublicationContext<GitLabRepoChangeParams>) =>
31
- <T>(name: string, args: Record<string, unknown> = {}) =>
32
- ctx.callIntegrationTool(name, { projectKey: "repo", ...args }) as Promise<T>;
22
+ const maintenanceAdapters = new WeakMap<
23
+ ExtensionProcessDefinition<GitLabRepoChangeParams, RepositoryChangeState>,
24
+ RepositoryChangePublicationAdapter<GitLabRepoChangeParams>
25
+ >();
26
+ /** @internal */
27
+ export function registerGitLabRepoChangeMaintenance(
28
+ api: ServerExtensionAPI,
29
+ process: ExtensionProcessDefinition<GitLabRepoChangeParams, RepositoryChangeState>,
30
+ ): void {
31
+ maintenanceAdapters.get(process)?.maintenance?.register(api, process);
32
+ }
33
33
  function requireRequest(state: RepositoryChangeState) {
34
34
  const current = remote(state);
35
35
  if (!current.prNumber || !current.headSha)
36
36
  throw new Error("Merge request delivery state is incomplete");
37
37
  return { ...current, prNumber: current.prNumber, headSha: current.headSha };
38
38
  }
39
+
39
40
  /** @public */
40
41
  export function gitlabPublicationEvidence(
41
42
  state: RepositoryChangeState,
42
43
  event: GitLabDeliveryObservation,
43
44
  ): PublicationEvidence {
44
- const current = requireRequest(state);
45
- const key = { observationKey: event.observationKey };
46
- if (event.mr.iid !== current.prNumber) throw new Error("Stale GitLab merge request evidence");
47
- if (event.mr.state === "merged" || event.mr.state === "closed")
48
- return { kind: "terminal", request: request(event.mr), ...key };
49
- if (event.mr.sha !== current.headSha) return { kind: "observed", ...key };
50
- if (event.conflict) return { kind: "conflict", conflict: event.conflict, ...key };
51
- if (event.feedback?.length)
52
- return {
53
- kind: "feedback",
54
- feedbackIds: event.feedback.map((n) => ({
55
- kind: "inline",
56
- id: n.id,
57
- discussionId: n.discussionId,
58
- })),
59
- conversationCursor: Math.max(current.conversationCursor, ...event.feedback.map((n) => n.id)),
60
- reviewCursor: 0,
61
- inlineCursor: 0,
62
- };
63
- if (event.pipeline && ["failed", "canceled"].includes(event.pipeline.status))
64
- return { kind: "failure", pipeline: { ...event.pipeline, number: event.pipeline.id }, ...key };
65
- return { kind: "observed", ...key };
45
+ return gitlabPublicationEvidenceForRequest(remote(state), event);
66
46
  }
47
+
67
48
  /** @public */
68
49
  export function createGitLabRepoChangeProcess(
69
50
  launcher: ReturnType<typeof createGitLabRepoChangeLauncher>,
70
51
  docker: boolean,
71
52
  ) {
72
53
  const sources: PublicationSource<GitLabRepoChangeParams>[] = [
73
- {
74
- id: "gitlab_merge_request",
75
- kind: "observation",
76
- label: "GitLab merge request evidence",
77
- source: gitlabExternal.mergeRequest(({ params, state }) => {
78
- const c = requireRequest(state);
79
- return {
80
- profile: params.gitlabProfile,
81
- projectId: params.projectId,
82
- iid: c.prNumber,
83
- pollInterval: "30s",
84
- afterKey: c.observationKey,
85
- feedback: { afterId: c.conversationCursor, quietPeriodMs: 120000 },
86
- delivery: {
87
- headSha: c.headSha,
88
- owner: params.owner,
89
- repo: params.repo,
90
- headBranch: params.workBranch,
91
- baseBranch: params.baseBranch,
92
- lastConflictKey: c.lastConflictKey,
93
- },
94
- };
95
- }),
96
- read: ({ state, event }) =>
97
- gitlabPublicationEvidence(state, event as GitLabDeliveryObservation),
98
- },
99
54
  {
100
55
  id: "source_cancelled",
101
56
  kind: "cancelled",
102
57
  label: "GitLab source issue cancelled",
103
- enabled: (p) => p.origin === "issue",
58
+ enabled: (params, state) =>
59
+ params.origin === "issue" && !!remote(state).prNumber && !!remote(state).headSha,
104
60
  source: gitlabExternal.issueCancelled(({ params, state }) => {
105
61
  if (params.origin !== "issue") throw new Error("Missing GitLab source issue");
106
62
  return {
107
63
  profile: params.gitlabProfile,
64
+ origin: params.gitlabOrigin,
108
65
  projectId: params.projectId,
109
66
  issueIid: params.issueNumber,
110
67
  iid: requireRequest(state).prNumber,
@@ -115,111 +72,8 @@ export function createGitLabRepoChangeProcess(
115
72
  read: () => ({ kind: "cancelled" }),
116
73
  },
117
74
  ];
118
- const publication = createRepositoryChangePublication<GitLabRepoChangeParams>({
119
- namespace: "gitlabRepoChange",
120
- label: "GitLab MR",
121
- ids: {
122
- deliver: "deliver_change",
123
- feedback: "revise_from_merge_request_feedback",
124
- ciRepair: "repair_gitlab_pipeline",
125
- operator: "ci_operator_action",
126
- },
127
- sources,
128
- tools: {
129
- delivery: [
130
- "gitlab_ensure_merge_request",
131
- "gitlab_observe_merge_request",
132
- "gitlab_comment",
133
- "gitlab_reply",
134
- "gitlab_get_identity",
135
- "gitlab_acknowledge_feedback",
136
- "gitlab_add_issue_comment",
137
- "gitlab_finalize_source_issue",
138
- ],
139
- feedback: [
140
- "gitlab_observe_merge_request",
141
- "gitlab_get_changes",
142
- "gitlab_list_merge_request_feedback",
143
- ],
144
- ci: ["gitlab_observe_merge_request", "gitlab_list_failed_jobs", "gitlab_get_job_trace"],
145
- },
146
- async identity(ctx) {
147
- const pinned = object(
148
- ctx.projects.find((p) => p.key === "repo")?.metadata?.["leitwerk.gitIdentity"],
149
- );
150
- if (
151
- pinned.provider !== "gitlab" ||
152
- pinned.profile !== ctx.params.gitlabProfile ||
153
- typeof pinned.name !== "string" ||
154
- typeof pinned.email !== "string"
155
- )
156
- throw new Error("Pinned GitLab Git identity is unavailable");
157
- return { name: pinned.name, email: pinned.email };
158
- },
159
- async ensureRequest(ctx) {
160
- const mr = await callFor(ctx)<GitLabMergeRequest>("gitlab_ensure_merge_request", {
161
- title: ctx.process.title ?? "Leitwerk change",
162
- body: `${ctx.params.origin === "issue" ? `Implements ${ctx.params.issueUrl}\n\n` : ""}Leitwerk process: ${ctx.process.id}`,
163
- });
164
- return request(mr);
165
- },
166
- async reconcileTerminal(ctx, _current, pr) {
167
- if (ctx.params.origin !== "issue") return;
168
- const call = callFor(ctx);
169
- await call("gitlab_finalize_source_issue", {
170
- issueNumber: ctx.params.issueNumber,
171
- merged: pr.merged,
172
- triggerLabel: ctx.params.triggerLabel,
173
- doneLabel: ctx.params.doneLabel,
174
- writeKey: `gitlab:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`,
175
- });
176
- await call("gitlab_add_issue_comment", {
177
- issueNumber: ctx.params.issueNumber,
178
- body: pr.merged
179
- ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.`
180
- : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
181
- writeKey: `gitlab:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-mr-comment`,
182
- });
183
- },
184
- async linkIssue(ctx, current) {
185
- if (ctx.params.origin === "issue")
186
- await callFor(ctx)("gitlab_add_issue_comment", {
187
- issueNumber: ctx.params.issueNumber,
188
- body: `Leitwerk opened merge request ${current.prUrl}.`,
189
- writeKey: `gitlab:${ctx.process.id}:source-mr-link:${current.prNumber}`,
190
- });
191
- },
192
- async acknowledge(ctx, current) {
193
- for (const feedback of current.feedbackIds)
194
- await callFor(ctx)("gitlab_acknowledge_feedback", { noteId: feedback.id });
195
- },
196
- async reply(ctx, current) {
197
- for (const feedback of current.feedbackIds) {
198
- if (!feedback.discussionId) throw new Error("GitLab feedback discussion is missing");
199
- await callFor(ctx)("gitlab_reply", {
200
- discussionId: feedback.discussionId,
201
- body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
202
- writeKey: `gitlab:${ctx.process.id}:feedback-reply:${feedback.id}:${current.headSha}`,
203
- });
204
- }
205
- },
206
- async head(ctx) {
207
- return (await callFor(ctx)<GitLabDeliveryObservation>("gitlab_observe_merge_request")).mr.sha;
208
- },
209
- async afterRebase(ctx, current) {
210
- await callFor(ctx)("gitlab_comment", {
211
- body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
212
- writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`,
213
- });
214
- },
215
- commitMessage: (kind) =>
216
- kind === "feedback" ? "fix: address GitLab review feedback" : "fix: repair GitLab pipeline",
217
- prompt(kind, current) {
218
- return kind === "feedback"
219
- ? `Address the unseen GitLab feedback for MR !${current.prNumber}: ${JSON.stringify(current.feedbackIds)}. Read the full discussions with gitlab_list_merge_request_feedback, inspect the checkout, and make only justified changes. Call changes_ready when ready to publish, no_changes with an explicit diagnosis when no change is needed, or cannot_repair for operator action.`
220
- : `Diagnose GitLab pipeline ${current.pipeline?.number} for head ${current.headSha}. Read gitlab_list_failed_jobs with pipelineId and bounded gitlab_get_job_trace before making repository repairs. Call changes_ready to publish, no_changes with a justified diagnosis, or cannot_repair when operator action is needed.`;
221
- },
222
- });
75
+ const adapter = createGitLabPublicationAdapter<GitLabRepoChangeParams>(sources);
76
+ const publication = createRepositoryChangePublication(adapter);
223
77
  publication.fragment.watcher({
224
78
  id: "use_leitwerk",
225
79
  label: "GitLab use-leitwerk issues",
@@ -233,17 +87,19 @@ export function createGitLabRepoChangeProcess(
233
87
  displayName: "GitLab Repo Change",
234
88
  paramsCodec: gitlabRepoChangeParamsCodec,
235
89
  launcher: launcher.launcher,
236
- finalizeLabel: "Publish merge request",
237
- finalizeForm: {
238
- id: "gitlab_publish",
239
- title: "Publish merge request",
240
- fields: [],
241
- submitLabel: "Publish",
242
- },
90
+ workflow: launcher.workflow,
243
91
  repositoryCredentials: ({ params, projects }) =>
244
- gitlabRepositoryCredentials(params.gitlabProfile, projects),
92
+ projects.map((project) => {
93
+ if (!params.gitSshProfile) throw new Error("Missing Git SSH profile");
94
+ return {
95
+ projectKey: project.key,
96
+ kind: "git_ssh" as const,
97
+ credentialRef: params.gitSshProfile,
98
+ };
99
+ }),
245
100
  publication,
246
101
  });
247
102
  definition.process.runtime = { ...definition.process.runtime, docker };
103
+ maintenanceAdapters.set(definition.process, adapter);
248
104
  return definition.process;
249
105
  }