@leitwerk-dev/gitlab 0.4.0 → 0.4.2

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.
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  applyPublicationEvidence,
3
3
  createPublicationSelection,
4
- type PublicationContext,
5
4
  type PublicationEvidence,
5
+ type PublicationReconciliationContext,
6
6
  patchPublicationState,
7
7
  publicationFinished,
8
8
  type RepositoryChangePublicationAdapter,
@@ -14,6 +14,7 @@ import { conflictKey } from "@leitwerk-dev/coding/repository-rebase";
14
14
  import type { ExtensionProcessDefinition, ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
15
15
  import { type GitLabMaintenanceContext, registerGitLabMaintainedProcess } from "./maintenance.js";
16
16
  import {
17
+ assertGitLabBranchBinding,
17
18
  type GitLabPublicationParams,
18
19
  gitlabPublicationEvidenceForRequest,
19
20
  gitlabPublicationRequest,
@@ -46,35 +47,20 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
46
47
  adapter.repositories?.(ctx.params) ?? [{ key: "repo", params: ctx.params }];
47
48
  const results = (ctx: GitLabMaintenanceContext<P, RepositoryChangeState>) =>
48
49
  repositories(ctx).map(({ key }) => ({ key, current: current(ctx, key) }));
49
- const workerContext = (
50
+ const reconciliationContext = (
50
51
  ctx: GitLabMaintenanceContext<P, RepositoryChangeState>,
51
52
  key: string,
52
- ): PublicationContext<P> =>
53
- ({
54
- ...ctx,
55
- params: params(ctx, key),
56
- state: select(ctx.state, key),
57
- repo: {
58
- get: (name: string) => {
59
- const project = ctx.projects.find(
60
- (project) => project.key === (name === "repo" ? key : name),
61
- );
62
- if (!project) throw new Error("Maintained process project is unavailable");
63
- return { ...project, fsPath: "", workBranch: project.workBranch ?? project.baseBranch };
64
- },
65
- },
66
- callIntegrationTool: (name: string, args: Record<string, unknown>) =>
67
- ctx.callIntegrationTool(name, { ...args, projectKey: key }),
68
- }) as unknown as PublicationContext<P>;
53
+ ): PublicationReconciliationContext<P> => ({
54
+ ...ctx,
55
+ params: params(ctx, key),
56
+ state: select(ctx.state, key),
57
+ callIntegrationTool: (name, args) =>
58
+ ctx.callIntegrationTool(name, { ...args, projectKey: key }),
59
+ });
69
60
  registerGitLabMaintainedProcess(api, {
70
61
  processId: process.id,
71
62
  paramsCodec: process.paramsCodec,
72
63
  stateCodec: process.stateCodec,
73
- destinations: {
74
- feedback: "maintenance_feedback",
75
- conflict: "maintenance_conflict",
76
- ci: "maintenance_ci",
77
- },
78
64
  idleTurnId: adapter.ids.deliver,
79
65
  currentBinding: (ctx) => (adapter.repositories ? selection.activeKey(ctx.state) : "repo"),
80
66
  settings: (ctx, binding) => ({
@@ -87,17 +73,39 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
87
73
  let value = current(ctx, key);
88
74
  const p = params(ctx, key);
89
75
  if (publicationFinished(value)) return { state: ctx.state };
76
+ if (observed.mr.state === "opened")
77
+ assertGitLabBranchBinding(observed.mr, p, binding.projectId);
78
+ // Observations never change an active worker's baseline or checkout.
79
+ if (
80
+ !ctx.process.currentExecution &&
81
+ !value.delivery.adjustment &&
82
+ observed.mr.sha !== value.headSha
83
+ ) {
84
+ value = {
85
+ ...value,
86
+ workBaselineSha: value.workBaselineSha ?? value.headSha,
87
+ lastPublishedHeadSha: value.lastPublishedHeadSha ?? value.headSha,
88
+ headSha: observed.mr.sha,
89
+ pipeline: null,
90
+ conflict: null,
91
+ lastConflictKey: null,
92
+ // A result verified against an older tree cannot acknowledge a rewritten source.
93
+ delivery: { ...value.delivery, feedbackResult: null },
94
+ };
95
+ ctx = { ...ctx, state: patch(ctx, key, value) };
96
+ }
90
97
  if (
91
98
  ctx.process.selectedTurnId === adapter.ids.deliver &&
92
99
  !ctx.process.currentExecution &&
93
100
  !value.delivery.adjustment &&
94
101
  !value.delivery.feedbackResult
95
102
  ) {
96
- if (value.feedbackIds.length) return { state: select(ctx.state, key), action: "feedback" };
103
+ if (value.feedbackIds.length)
104
+ return { state: select(ctx.state, key), action: "maintenance_feedback" };
97
105
  if (value.conflict && value.repairReason === "rebase")
98
- return { state: select(ctx.state, key), action: "conflict" };
106
+ return { state: select(ctx.state, key), action: "maintenance_conflict" };
99
107
  if (value.repairPending && value.repairReason === "ci" && value.pipeline)
100
- return { state: select(ctx.state, key), action: "ci" };
108
+ return { state: select(ctx.state, key), action: "maintenance_ci" };
101
109
  }
102
110
  // Preserve staged legacy evidence without replaying its old Deliver execution.
103
111
  let evidence: PublicationEvidence;
@@ -121,13 +129,7 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
121
129
  (observed.mr.has_conflicts ||
122
130
  ["conflict", "need_rebase"].includes(observed.mr.detailed_merge_status ?? ""))
123
131
  ) {
124
- if (
125
- observed.mr.source_project_id !== binding.projectId ||
126
- observed.mr.target_project_id !== binding.projectId ||
127
- observed.mr.source_branch !== p.workBranch ||
128
- observed.mr.target_branch !== p.baseBranch
129
- )
130
- throw new Error("GitLab maintenance branch binding changed");
132
+ assertGitLabBranchBinding(observed.mr, p, binding.projectId);
131
133
  const conflict = {
132
134
  owner: p.owner,
133
135
  repo: p.repo,
@@ -163,7 +165,7 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
163
165
  action,
164
166
  });
165
167
  if (evidence.kind === "feedback" || evidence.kind === "conflict")
166
- return dispatch(evidence.kind);
168
+ return dispatch(`maintenance_${evidence.kind}`);
167
169
  // Labels, mergeability and target-head changes do not create a new CI failure.
168
170
  // Keeping the last pipeline status also admits a retry that runs and fails again.
169
171
  if (
@@ -174,7 +176,7 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
174
176
  (evidence.pipeline.project_id ?? binding.projectId))
175
177
  ) {
176
178
  const operator = value.ciRecoveryCycles >= 3;
177
- return dispatch(operator ? "maintenance_operator" : "ci", operator);
179
+ return dispatch(operator ? "maintenance_operator" : "maintenance_ci", operator);
178
180
  }
179
181
  return {
180
182
  state: patch(ctx, key, {
@@ -255,7 +257,7 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
255
257
  cancelled: (ctx) =>
256
258
  Promise.resolve(
257
259
  adapter.sourceCancelled?.(
258
- workerContext(ctx, adapter.repositories?.(ctx.params)[0]?.key ?? "repo"),
260
+ reconciliationContext(ctx, adapter.repositories?.(ctx.params)[0]?.key ?? "repo"),
259
261
  ) ?? false,
260
262
  ),
261
263
  completion(ctx) {
@@ -271,7 +273,7 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
271
273
  const observed = results(ctx);
272
274
  if (adapter.reconcileAll)
273
275
  await adapter.reconcileAll(
274
- workerContext(ctx, observed[0].key),
276
+ reconciliationContext(ctx, observed[0].key),
275
277
  observed,
276
278
  !observed.every(({ current }) => publicationFinished(current)),
277
279
  );
@@ -279,7 +281,7 @@ export function registerGitLabPublicationMaintenance<P extends Partial<GitLabPub
279
281
  for (const { key, current } of observed)
280
282
  if (current.delivery.terminalPullRequest)
281
283
  await adapter.reconcileTerminal(
282
- workerContext(ctx, key),
284
+ reconciliationContext(ctx, key),
283
285
  current,
284
286
  current.delivery.terminalPullRequest,
285
287
  );
@@ -5,6 +5,7 @@ import {
5
5
  type PublicationRequest,
6
6
  type PublicationSource,
7
7
  type PublicationState,
8
+ type PublicationReconciliationContext as RemoteContext,
8
9
  type RepositoryChangePublicationAdapter,
9
10
  resolvePullRequestGitIdentity,
10
11
  } from "@leitwerk-dev/coding/repository-change-publication";
@@ -36,6 +37,21 @@ export interface GitLabPublicationParams extends PublicationParams {
36
37
  /** @internal */
37
38
  doneLabel?: string | null;
38
39
  }
40
+ /** @internal */
41
+ export function assertGitLabBranchBinding(
42
+ mr: GitLabMergeRequest,
43
+ params: Partial<GitLabPublicationParams>,
44
+ projectId = params.projectId,
45
+ ): void {
46
+ if (
47
+ mr.source_project_id !== projectId ||
48
+ mr.target_project_id !== projectId ||
49
+ mr.source_branch !== params.workBranch ||
50
+ mr.target_branch !== params.baseBranch
51
+ )
52
+ throw new Error("GitLab maintenance branch binding changed");
53
+ }
54
+
39
55
  /** @internal */
40
56
  export const gitlabPublicationRequest = (mr: GitLabMergeRequest): PublicationRequest => ({
41
57
  number: mr.iid,
@@ -85,11 +101,10 @@ export function gitlabPublicationEvidenceForRequest(
85
101
  const current = state;
86
102
  if (!current.prNumber || !current.headSha)
87
103
  throw new Error("Merge request delivery state is incomplete");
88
- const key = { observationKey: event.observationKey };
104
+ const key = { observationKey: event.observationKey, remoteHeadSha: event.mr.sha };
89
105
  if (event.mr.iid !== current.prNumber) throw new Error("Stale GitLab merge request evidence");
90
106
  if (event.mr.state === "merged" || event.mr.state === "closed")
91
107
  return { kind: "terminal", request: gitlabPublicationRequest(event.mr), ...key };
92
- if (event.mr.sha !== current.headSha) return { kind: "observed", ...key };
93
108
  if (event.conflict) return { kind: "conflict", conflict: event.conflict, ...key };
94
109
  if (event.feedback?.length)
95
110
  return {
@@ -103,8 +118,12 @@ export function gitlabPublicationEvidenceForRequest(
103
118
  conversationCursor: Math.max(current.conversationCursor, ...event.feedback.map((n) => n.id)),
104
119
  reviewCursor: 0,
105
120
  inlineCursor: 0,
121
+ remoteHeadSha: event.mr.sha,
106
122
  };
107
- if (event.pipeline?.status === "failed")
123
+ if (
124
+ event.pipeline?.status === "failed" &&
125
+ (event.pipeline.sha === event.mr.sha || event.pipelineSourceHead === event.mr.sha)
126
+ )
108
127
  return { kind: "failure", pipeline: { ...event.pipeline, number: event.pipeline.id }, ...key };
109
128
  return { kind: "observed", ...key };
110
129
  }
@@ -119,7 +138,7 @@ export function createGitLabPublicationAdapter<P extends Partial<GitLabPublicati
119
138
  body: `${ctx.params.origin === "issue" ? `Implements ${ctx.params.issueUrl}\n\n` : ""}Leitwerk process: ${ctx.process.id}`,
120
139
  }),
121
140
  ): RepositoryChangePublicationAdapter<P> {
122
- async function finalizeIssue(ctx: PublicationContext<P>, pr: PublicationRequest | null) {
141
+ async function finalizeIssue(ctx: RemoteContext<P>, pr: PublicationRequest | null) {
123
142
  if (ctx.params.origin !== "issue") return;
124
143
  const call = callFor(ctx);
125
144
  await call("gitlab_finalize_source_issue", {
@@ -187,6 +206,7 @@ export function createGitLabPublicationAdapter<P extends Partial<GitLabPublicati
187
206
  if (!current.prNumber && !(project?.metadata?.gitlab as { iid?: number } | undefined)?.iid)
188
207
  return null;
189
208
  const { mr } = await callFor(ctx)<GitLabDeliveryObservation>("gitlab_observe_merge_request");
209
+ if (mr.state === "opened") assertGitLabBranchBinding(mr, ctx.params);
190
210
  return mr.state === "opened" ? null : gitlabPublicationRequest(mr);
191
211
  },
192
212
  reconcileTerminal: (ctx, _current, pr) => finalizeIssue(ctx, pr),
package/src/testing.ts CHANGED
@@ -47,6 +47,8 @@ interface LocalState {
47
47
  discussionResolved?: Record<string, boolean>;
48
48
  /** @public */
49
49
  reactions?: Record<string, GitLabNoteReaction[]>;
50
+ /** SHA the bot approved. Stays set across later commits until unapprove. @public */
51
+ approvedSha?: Record<string, string>;
50
52
  }
51
53
  /** Persistent GitLab test boundary. Repository URLs use local Git's file transport. */
52
54
  /** @public */
@@ -66,6 +68,8 @@ export class LocalGitLabAdapter {
66
68
  /** @public */
67
69
  loseNextLabelResponse = false;
68
70
  /** @public */
71
+ loseNextApprovalResponse = false;
72
+ /** @public */
69
73
  constructor(
70
74
  /** @internal */
71
75
  readonly root: string,
@@ -352,10 +356,44 @@ export class LocalGitLabAdapter {
352
356
  has_conflicts: this.conflicts(mr(id, iid)),
353
357
  sha: this.git(mr(id, iid).source_project_id, ["rev-parse", mr(id, iid).source_branch]),
354
358
  }),
359
+ getMergeRequestApprovals: async (id, iid) => ({
360
+ user_has_approved: this.state.approvedSha?.[`${id}:${iid}`] !== undefined,
361
+ }),
362
+ approveMergeRequest: async (id, iid, sha) => {
363
+ const request = mr(id, iid);
364
+ const head = commit(request.source_project_id, request.source_branch).id;
365
+ if (head !== sha) throw new Error("SHA does not match HEAD of source branch");
366
+ const key = `${id}:${iid}`;
367
+ this.state.approvedSha ??= {};
368
+ if (this.state.approvedSha[key] === sha) return { sha };
369
+ this.state.approvedSha[key] = sha;
370
+ this.save();
371
+ if (this.loseNextApprovalResponse) {
372
+ this.loseNextApprovalResponse = false;
373
+ throw new Error("Response lost after approval");
374
+ }
375
+ return { sha };
376
+ },
377
+ unapproveMergeRequest: async (id, iid) => {
378
+ const request = mr(id, iid);
379
+ const head = commit(request.source_project_id, request.source_branch).id;
380
+ const key = `${id}:${iid}`;
381
+ if (this.state.approvedSha?.[key] === undefined) return { sha: head };
382
+ delete this.state.approvedSha[key];
383
+ this.save();
384
+ if (this.loseNextApprovalResponse) {
385
+ this.loseNextApprovalResponse = false;
386
+ throw new Error("Response lost after unapprove");
387
+ }
388
+ return { sha: head };
389
+ },
355
390
  listMergeRequests: async (id, label) =>
356
391
  structuredClone(
357
392
  this.state.mrs.filter(
358
- (m) => m.project_id === id && m.state === "opened" && m.labels.includes(label),
393
+ (m) =>
394
+ (id === null || m.project_id === id) &&
395
+ m.state === "opened" &&
396
+ label.split(",").every((name) => m.labels.includes(name)),
359
397
  ),
360
398
  ),
361
399
  listMergeRequestLabelEvents: async (id, iid) => {
package/src/tools.ts CHANGED
@@ -336,6 +336,109 @@ export async function ensureGitLabResolveDiscussion(input: {
336
336
  );
337
337
  return { discussionId, resolved: true };
338
338
  }
339
+ /** @internal */
340
+ export async function ensureGitLabApproval(input: {
341
+ /** @internal */
342
+ client: GitLabClientLike;
343
+ /** @internal */
344
+ writes: ExternalWrites;
345
+ /** @internal */
346
+ instanceId: string;
347
+ /** @internal */
348
+ projectId: number;
349
+ /** @internal */
350
+ iid: number;
351
+ /** @internal */
352
+ writeKey: string;
353
+ /** @internal */
354
+ sha: string;
355
+ /** @internal */
356
+ signal?: AbortSignal;
357
+ }): Promise<{ sha: string; approved: boolean }> {
358
+ const { client, writes, instanceId, projectId, iid, writeKey, sha, signal } = input;
359
+ if (!/^[a-f0-9]{40}$/i.test(sha)) throw new Error("GitLab approval requires the full source SHA");
360
+ const current = await client.getMergeRequest(projectId, iid, signal);
361
+ if (current.sha !== sha) return { sha, approved: false };
362
+ const digest = hashIdentity([
363
+ client.baseUrl,
364
+ projectId,
365
+ iid,
366
+ instanceId,
367
+ "approve",
368
+ writeKey,
369
+ sha,
370
+ ]);
371
+ await writes.ensure(
372
+ { writeType: "gitlab.approval", dedupKey: digest },
373
+ {
374
+ reconcile: async () => {
375
+ const head = await client.getMergeRequest(projectId, iid, signal);
376
+ const approvals = await client.getMergeRequestApprovals(projectId, iid, signal);
377
+ return head.sha === sha && approvals.user_has_approved ? { sha } : null;
378
+ },
379
+ execute: () => client.approveMergeRequest(projectId, iid, sha, signal),
380
+ toMetadata: (approval) => ({ projectId, iid, sha: approval.sha }),
381
+ },
382
+ );
383
+ return { sha, approved: true };
384
+ }
385
+ /** @internal */
386
+ export async function ensureGitLabUnapproval(input: {
387
+ /** @internal */
388
+ client: GitLabClientLike;
389
+ /** @internal */
390
+ writes: ExternalWrites;
391
+ /** @internal */
392
+ instanceId: string;
393
+ /** @internal */
394
+ projectId: number;
395
+ /** @internal */
396
+ iid: number;
397
+ /** @internal */
398
+ writeKey: string;
399
+ /** @internal */
400
+ sha: string;
401
+ /** @internal */
402
+ signal?: AbortSignal;
403
+ }): Promise<{ sha: string; unapproved: boolean }> {
404
+ const { client, writes, instanceId, projectId, iid, writeKey, sha, signal } = input;
405
+ if (!/^[a-f0-9]{40}$/i.test(sha))
406
+ throw new Error("GitLab unapprove requires the full source SHA");
407
+ const current = await client.getMergeRequest(projectId, iid, signal);
408
+ if (current.sha !== sha) return { sha, unapproved: false };
409
+ const digest = hashIdentity([
410
+ client.baseUrl,
411
+ projectId,
412
+ iid,
413
+ instanceId,
414
+ "unapprove",
415
+ writeKey,
416
+ sha,
417
+ ]);
418
+ try {
419
+ await writes.ensure(
420
+ { writeType: "gitlab.unapproval", dedupKey: digest },
421
+ {
422
+ reconcile: async () => {
423
+ const head = await client.getMergeRequest(projectId, iid, signal);
424
+ const approvals = await client.getMergeRequestApprovals(projectId, iid, signal);
425
+ return head.sha === sha && !approvals.user_has_approved ? { sha } : null;
426
+ },
427
+ execute: async () => {
428
+ const head = await client.getMergeRequest(projectId, iid, signal);
429
+ if (head.sha !== sha) throw new Error("GitLab source SHA is no longer HEAD");
430
+ return client.unapproveMergeRequest(projectId, iid, signal);
431
+ },
432
+ toMetadata: (removed) => ({ projectId, iid, sha: removed.sha }),
433
+ },
434
+ );
435
+ } catch (error) {
436
+ if ((await client.getMergeRequest(projectId, iid, signal)).sha !== sha)
437
+ return { sha, unapproved: false };
438
+ throw error;
439
+ }
440
+ return { sha, unapproved: true };
441
+ }
339
442
  /** @public */
340
443
  export async function ensureGitLabSeenReaction(input: {
341
444
  /** @public */
@@ -492,6 +595,16 @@ export function registerGitLabTools(
492
595
  "Resolve a retry-safe MR inline discussion",
493
596
  ["writeKey", "discussionId"],
494
597
  ],
598
+ [
599
+ "gitlab_approve_merge_request",
600
+ "Approve the bound MR at an exact source SHA",
601
+ ["writeKey", "sha"],
602
+ ],
603
+ [
604
+ "gitlab_unapprove_merge_request",
605
+ "Remove the bot approval while the reviewed source SHA is still HEAD",
606
+ ["writeKey", "sha"],
607
+ ],
495
608
  ] as const) {
496
609
  api.tool<Record<string, unknown>>({
497
610
  name,
@@ -510,6 +623,7 @@ export function registerGitLabTools(
510
623
  baseSha: { type: "string" },
511
624
  startSha: { type: "string" },
512
625
  headSha: { type: "string" },
626
+ sha: { type: "string" },
513
627
  },
514
628
  [...required],
515
629
  ),
@@ -567,6 +681,18 @@ export function registerGitLabTools(
567
681
  writeKey: stringArg(args, "writeKey"),
568
682
  discussionId: stringArg(args, "discussionId"),
569
683
  });
684
+ if (name === "gitlab_approve_merge_request")
685
+ return ensureGitLabApproval({
686
+ ...writeContext,
687
+ writeKey: stringArg(args, "writeKey"),
688
+ sha: stringArg(args, "sha"),
689
+ });
690
+ if (name === "gitlab_unapprove_merge_request")
691
+ return ensureGitLabUnapproval({
692
+ ...writeContext,
693
+ writeKey: stringArg(args, "writeKey"),
694
+ sha: stringArg(args, "sha"),
695
+ });
570
696
  const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
571
697
  if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
572
698
  throw new Error("Pipeline is not current for the authorized MR");