@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.
package/README.md CHANGED
@@ -58,11 +58,12 @@ extensions:
58
58
  remote reads; unknown names display the stable repository ID until found.
59
59
  Admission and delivery still read live project metadata and permissions through
60
60
  `client(profile)`.
61
+ - `listMergeRequests(projectId, labels)` reads open MRs matching every comma-separated label. Pass `null` for `projectId` to query all accessible projects without enumerating repositories. Both forms use `scope=all`, not only MRs authored by the token owner.
61
62
  - `listMergeRequestLabelEvents()` reads paginated label transitions with stable event IDs. `updateMergeRequestLabels()` applies `add_labels` and `remove_labels` without replacing unrelated labels.
62
63
  - `registerGitLabMaintainedProcess()` registers a typed MR maintenance policy through
63
64
  the capability registry. One server service observes all registered processes,
64
65
  including running turns and operator waits. The process supplies its repair
65
- destinations, state adapters, completion policy and optional retry budget.
66
+ destinations, state adapters and completion policy.
66
67
  - `gitlabRepositoryCredentials(profile, projects)` derives internal credential references. The core authorizes their HTTPS origin and exact repository path against the process projects.
67
68
  - `selectGitLabProjects()` expands exact includes and groups, including subgroups, then applies exclusions. Includes form a union; stable project IDs remove duplicates. An explicit include or `all_accessible: true` is required.
68
69
  - `observeMergeRequest()` selects the newest pipeline associated with the current MR source revision. Synthetic merge commits must contain that head as a parent. With no matching MR pipeline, it falls back to the current source branch's push pipeline. A newer pending result supersedes older terminal results. The observation includes GitLab's `has_conflicts`, `merge_status` and `detailed_merge_status`, plus `targetHead` read from the current target branch (not the historical diff base). Closed MRs do not require branch or pipeline reads.
@@ -102,6 +103,8 @@ conflict observations remain available.
102
103
 
103
104
  `ensureGitLabSeenReaction()` lets a process acknowledge an authorized MR comment with an eyes reaction. It reconciles the authenticated bot's reaction and records it with `ctx.externalWrites.ensure()`. Other users' eyes reactions do not suppress the bot's acknowledgement; retries and restarts do not duplicate it. The calling process owns selection and lifecycle checks.
104
105
 
106
+ `gitlab_approve_merge_request` approves the bound MR when its current source SHA matches the supplied full SHA. The write key includes that SHA. A repeated call reconciles the bot's existing approval and does not approve again. A SHA that is no longer HEAD is left unapproved. `gitlab_unapprove_merge_request` removes that approval when the same SHA is still HEAD. A repeated call does not unapprove again. A moved HEAD is left unchanged so the next review can decide.
107
+
105
108
  The extension contains no Renovate selection or repair policy. `./testing` exports a persistent `LocalGitLabAdapter` with real local repository ancestry for integration tests.
106
109
 
107
110
  ## Shared MR maintenance
@@ -115,11 +118,6 @@ registerGitLabMaintainedProcess(api, {
115
118
  paramsCodec: process.paramsCodec,
116
119
  stateCodec: process.stateCodec,
117
120
  idleTurnId: "deliver_change",
118
- destinations: {
119
- feedback: "maintenance_feedback",
120
- conflict: "maintenance_conflict",
121
- ci: "maintenance_ci",
122
- },
123
121
  observe: repairPolicy.observe,
124
122
  stopped: repairPolicy.stopped,
125
123
  terminal: repairPolicy.terminal,
@@ -132,9 +130,9 @@ Bindings default to each process project's `gitlab` metadata. `bindings` can
132
130
  provide explicit MR targets. `settings` supplies the consumed feedback cursor,
133
131
  activation receipt, polling interval and quiet period; the quiet period defaults
134
132
  to two minutes. `assess`, `eligible` and `canWrite` retain process-specific admission
135
- rules. `observe` returns state and an optional destination key (`feedback`,
136
- `conflict`, `ci`) or an additional declared external action. The service fires the
137
- existing edge; ordinary observations allocate no worker and create no turn record.
133
+ rules. `observe` returns state and an optional declared external action ID, such
134
+ as `maintenance_feedback`. It replaces the former `destinations` alias mapping.
135
+ The service fires that edge; ordinary observations allocate no worker or turn record.
138
136
  `currentBinding` identifies a selected repair or operator decision so removing a
139
137
  different MR's label preserves that business position. Interrupted repairs on
140
138
  remaining MRs retain their staged work and repair budgets.
@@ -142,8 +140,15 @@ remaining MRs retain their staged work and repair budgets.
142
140
  `messages` supplies retry-safe discussion replies or comments. `settled` advances
143
141
  business acknowledgement state after those writes succeed. `completion` determines
144
142
  the terminal lifecycle without remote writes. `complete` delivers process-specific
145
- terminal writes and retries them after the process ends. Optional `retry.maxAttempts`
146
- bounds generic infrastructure retries without consuming the process's repair budget.
143
+ terminal writes and retries them after the process ends.
144
+
145
+ Eligible, owned bindings request server-managed recovery for failed unaccepted
146
+ worker starts. The server allows three starts per episode, with 30/60 second
147
+ retry delays for known transient failures. Configuration errors, OOMs and unknown
148
+ failures require manual recovery. Accepted failed turns are never retried by
149
+ maintenance. Recovery does not consume the process's business repair budget.
150
+ The deprecated `retry.maxAttempts` setting is ignored; maintenance cannot override
151
+ the server's startup budget.
147
152
 
148
153
  Taking responsibility adds `leitwerk-active`. Green CI keeps maintenance active for
149
154
  later feedback. Removing the label ends that MR's activation and leaves the MR open.
@@ -166,11 +171,27 @@ Processes retain their own reactivation admission and partial-completion rules.
166
171
  The shared publication adapter used by Jira and GitLab repository changes registers
167
172
  this policy. Settled feedback and actionable conflicts invoke Address Feedback
168
173
  directly; failed current-revision CI invokes Fix CI. Changed work returns to Deliver.
169
- A no-change outcome acknowledges its batch and resumes observation without another
170
- Deliver execution. Label, target-head and mergeability updates do not replay a
174
+ A no-change outcome returns through Deliver to check concurrent source updates and
175
+ retained local work before acknowledging its batch. An unchanged checkout creates
176
+ no commit or push. Label, target-head and mergeability updates do not replay a
171
177
  handled pipeline failure. A new pipeline or an observed running-to-failed retry
172
178
  remains actionable. Maintenance adds no business turns.
173
179
 
180
+ The current source branch is authoritative, including developer rebases and pushes.
181
+ Idle observations adopt its head while retaining the earlier work baseline and
182
+ publication receipt separately. Feedback stays actionable when the head changes;
183
+ the worker reconciles unpublished local work before adjusting the current revision.
184
+ Source/target project or branch changes are explicit binding errors, not permission
185
+ to publish elsewhere. Active workers keep their captured state; delivery rechecks
186
+ the branch after their work. Only pipelines associated with the current source
187
+ revision or a merge-result commit containing it can trigger repair.
188
+
189
+ An eyes reaction means the watcher saw an authorized comment. It does not mean a
190
+ worker started, completed an adjustment, or consumed the feedback. Comments remain
191
+ pending until publication or a verified no-change result is acknowledged. Conflict
192
+ resolution, validation retries and safe publication use the shared
193
+ [Coding reconciliation contract](../coding/README.md#source-branch-reconciliation).
194
+
174
195
  ## Creating repository changes
175
196
 
176
197
  Load [gitlab-repo-change](../gitlab-repo-change/README.md) for UI and labeled-issue
@@ -333,17 +333,27 @@ var GitLabClient = class {
333
333
  signal
334
334
  );
335
335
  }
336
- /** @public */
336
+ /** Open MRs matching every comma-separated label; null selects all accessible projects. @public */
337
337
  listMergeRequests(id, label, signal) {
338
- return this.pages(
339
- `${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
340
- signal
341
- );
338
+ const path = id === null ? "/merge_requests" : `${projectPath(id)}/merge_requests`;
339
+ return this.pages(`${path}?state=opened&scope=all&labels=${encodeURIComponent(label)}`, signal);
342
340
  }
343
341
  /** @internal */
344
342
  getMergeRequest(id, iid, signal) {
345
343
  return this.request(mrPath(id, iid), signal);
346
344
  }
345
+ /** @internal */
346
+ getMergeRequestApprovals(id, iid, signal) {
347
+ return this.request(`${mrPath(id, iid)}/approvals`, signal);
348
+ }
349
+ /** @internal */
350
+ approveMergeRequest(id, iid, sha, signal) {
351
+ return this.request(`${mrPath(id, iid)}/approve`, signal, { sha });
352
+ }
353
+ /** @internal */
354
+ unapproveMergeRequest(id, iid, signal) {
355
+ return this.request(`${mrPath(id, iid)}/unapprove`, signal, {});
356
+ }
347
357
  /** Read every label transition, including changes between watcher polls. @public */
348
358
  listMergeRequestLabelEvents(id, iid, signal) {
349
359
  return this.pages(`${mrPath(id, iid)}/resource_label_events`, signal);
@@ -527,7 +537,12 @@ async function observeMergeRequest(client, projectId, iid, signal) {
527
537
  matches = commit.parent_ids.includes(mr.sha);
528
538
  }
529
539
  if (matches)
530
- return { mr, targetHead, pipeline: await client.getPipeline(id, candidate.id, signal) };
540
+ return {
541
+ mr,
542
+ targetHead,
543
+ pipeline: await client.getPipeline(id, candidate.id, signal),
544
+ pipelineSourceHead: mr.sha
545
+ };
531
546
  }
532
547
  const candidates = await client.listBranchPipelines(
533
548
  mr.source_project_id,
@@ -539,7 +554,8 @@ async function observeMergeRequest(client, projectId, iid, signal) {
539
554
  return {
540
555
  mr,
541
556
  targetHead,
542
- pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null
557
+ pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null,
558
+ ...latest ? { pipelineSourceHead: mr.sha } : {}
543
559
  };
544
560
  }
545
561
 
@@ -747,6 +763,73 @@ async function ensureGitLabResolveDiscussion(input) {
747
763
  );
748
764
  return { discussionId, resolved: true };
749
765
  }
766
+ async function ensureGitLabApproval(input) {
767
+ const { client, writes, instanceId, projectId, iid, writeKey, sha, signal } = input;
768
+ if (!/^[a-f0-9]{40}$/i.test(sha)) throw new Error("GitLab approval requires the full source SHA");
769
+ const current = await client.getMergeRequest(projectId, iid, signal);
770
+ if (current.sha !== sha) return { sha, approved: false };
771
+ const digest = hashIdentity([
772
+ client.baseUrl,
773
+ projectId,
774
+ iid,
775
+ instanceId,
776
+ "approve",
777
+ writeKey,
778
+ sha
779
+ ]);
780
+ await writes.ensure(
781
+ { writeType: "gitlab.approval", dedupKey: digest },
782
+ {
783
+ reconcile: async () => {
784
+ const head = await client.getMergeRequest(projectId, iid, signal);
785
+ const approvals = await client.getMergeRequestApprovals(projectId, iid, signal);
786
+ return head.sha === sha && approvals.user_has_approved ? { sha } : null;
787
+ },
788
+ execute: () => client.approveMergeRequest(projectId, iid, sha, signal),
789
+ toMetadata: (approval) => ({ projectId, iid, sha: approval.sha })
790
+ }
791
+ );
792
+ return { sha, approved: true };
793
+ }
794
+ async function ensureGitLabUnapproval(input) {
795
+ const { client, writes, instanceId, projectId, iid, writeKey, sha, signal } = input;
796
+ if (!/^[a-f0-9]{40}$/i.test(sha))
797
+ throw new Error("GitLab unapprove requires the full source SHA");
798
+ const current = await client.getMergeRequest(projectId, iid, signal);
799
+ if (current.sha !== sha) return { sha, unapproved: false };
800
+ const digest = hashIdentity([
801
+ client.baseUrl,
802
+ projectId,
803
+ iid,
804
+ instanceId,
805
+ "unapprove",
806
+ writeKey,
807
+ sha
808
+ ]);
809
+ try {
810
+ await writes.ensure(
811
+ { writeType: "gitlab.unapproval", dedupKey: digest },
812
+ {
813
+ reconcile: async () => {
814
+ const head = await client.getMergeRequest(projectId, iid, signal);
815
+ const approvals = await client.getMergeRequestApprovals(projectId, iid, signal);
816
+ return head.sha === sha && !approvals.user_has_approved ? { sha } : null;
817
+ },
818
+ execute: async () => {
819
+ const head = await client.getMergeRequest(projectId, iid, signal);
820
+ if (head.sha !== sha) throw new Error("GitLab source SHA is no longer HEAD");
821
+ return client.unapproveMergeRequest(projectId, iid, signal);
822
+ },
823
+ toMetadata: (removed) => ({ projectId, iid, sha: removed.sha })
824
+ }
825
+ );
826
+ } catch (error) {
827
+ if ((await client.getMergeRequest(projectId, iid, signal)).sha !== sha)
828
+ return { sha, unapproved: false };
829
+ throw error;
830
+ }
831
+ return { sha, unapproved: true };
832
+ }
750
833
  async function ensureGitLabSeenReaction(input) {
751
834
  const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
752
835
  const digest = hashIdentity([client.baseUrl, projectId, iid, instanceId, "eyes", noteId]);
@@ -862,6 +945,16 @@ function registerGitLabTools(api, integration, beforeWrite) {
862
945
  "gitlab_resolve_discussion",
863
946
  "Resolve a retry-safe MR inline discussion",
864
947
  ["writeKey", "discussionId"]
948
+ ],
949
+ [
950
+ "gitlab_approve_merge_request",
951
+ "Approve the bound MR at an exact source SHA",
952
+ ["writeKey", "sha"]
953
+ ],
954
+ [
955
+ "gitlab_unapprove_merge_request",
956
+ "Remove the bot approval while the reviewed source SHA is still HEAD",
957
+ ["writeKey", "sha"]
865
958
  ]
866
959
  ]) {
867
960
  api.tool({
@@ -880,7 +973,8 @@ function registerGitLabTools(api, integration, beforeWrite) {
880
973
  side: { type: "string" },
881
974
  baseSha: { type: "string" },
882
975
  startSha: { type: "string" },
883
- headSha: { type: "string" }
976
+ headSha: { type: "string" },
977
+ sha: { type: "string" }
884
978
  },
885
979
  [...required]
886
980
  ),
@@ -936,6 +1030,18 @@ function registerGitLabTools(api, integration, beforeWrite) {
936
1030
  writeKey: stringArg(args, "writeKey"),
937
1031
  discussionId: stringArg(args, "discussionId")
938
1032
  });
1033
+ if (name === "gitlab_approve_merge_request")
1034
+ return ensureGitLabApproval({
1035
+ ...writeContext,
1036
+ writeKey: stringArg(args, "writeKey"),
1037
+ sha: stringArg(args, "sha")
1038
+ });
1039
+ if (name === "gitlab_unapprove_merge_request")
1040
+ return ensureGitLabUnapproval({
1041
+ ...writeContext,
1042
+ writeKey: stringArg(args, "writeKey"),
1043
+ sha: stringArg(args, "sha")
1044
+ });
939
1045
  const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
940
1046
  if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
941
1047
  throw new Error("Pipeline is not current for the authorized MR");
@@ -1700,9 +1806,8 @@ function createGitLabMaintenance(api, deps, integration, now = Date.now) {
1700
1806
  fresh = deps.processes.getById(process2.id);
1701
1807
  if (!fresh) continue;
1702
1808
  if (eligible && decision.action && fresh.lifecycleStatus === "waiting" && unchangedWork(fresh, ctx.process)) {
1703
- const destination = policy.destinations[decision.action] ?? decision.action;
1704
1809
  const armed = deps.externalSources.listArmed(policy.sourceKind ?? GITLAB_MAINTAINED_KIND).find(
1705
- (item) => item.instanceId === process2.id && item.externalActionId === destination
1810
+ (item) => item.instanceId === process2.id && item.externalActionId === decision.action
1706
1811
  );
1707
1812
  if (armed) {
1708
1813
  await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
@@ -1727,30 +1832,9 @@ function createGitLabMaintenance(api, deps, integration, now = Date.now) {
1727
1832
  if (!fresh.currentExecution && settledState !== ctx.state)
1728
1833
  await observe(fresh, { state: settledState });
1729
1834
  fresh = deps.processes.getById(process2.id);
1730
- if (fresh && eligible && policy.retry && fresh.lifecycleStatus === "error" && fresh.currentExecution) {
1731
- const retry = asUnknownRecord3(fresh.metadata?.gitlabMaintenanceRetry) ?? {};
1732
- const attempts = Number(retry.attempts ?? 0);
1733
- if (retry.executionId !== fresh.currentExecution.id) {
1734
- await observe(fresh, {
1735
- metadata: {
1736
- gitlabMaintenanceRetry: {
1737
- attempts,
1738
- executionId: fresh.currentExecution.id,
1739
- nextAt: now() + Math.min(3e5, 3e4 * 2 ** attempts),
1740
- attempted: false
1741
- }
1742
- },
1743
- preserveUpdatedAt: true
1744
- });
1745
- } else if (!retry.attempted && attempts < policy.retry.maxAttempts && Number(retry.nextAt) <= now()) {
1746
- await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
1747
- const saved2 = await observe(fresh, {
1748
- metadata: {
1749
- gitlabMaintenanceRetry: { ...retry, attempts: attempts + 1, attempted: true }
1750
- }
1751
- });
1752
- if (saved2.ok) await deps.commands.retryProcess(fresh.id);
1753
- }
1835
+ if (fresh && eligible && fresh.lifecycleStatus === "error" && fresh.currentExecution?.kind === "worker_start") {
1836
+ await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
1837
+ await deps.commands.retryStartupAutomatically(fresh.id, fresh.currentExecution.id);
1754
1838
  } else if (fresh?.lifecycleStatus === "waiting" && !fresh.currentExecution && fresh.selectedTurnId === policy.idleTurnId && fresh.metadata?.gitlabMaintenanceRetry) {
1755
1839
  await observe(fresh, {
1756
1840
  metadata: { gitlabMaintenanceRetry: null },
@@ -2340,4 +2424,4 @@ export {
2340
2424
  createGitLabRepositoryCatalog,
2341
2425
  setupGitLabIntegration
2342
2426
  };
2343
- //# sourceMappingURL=chunk-YPCOVBQS.js.map
2427
+ //# sourceMappingURL=chunk-KW4UOHAM.js.map