@leitwerk-dev/forgejo-repo-change 0.2.1 → 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/process.ts CHANGED
@@ -1,22 +1,21 @@
1
1
  import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
2
- import { commitAndPushWorkBranch } from "@leitwerk-dev/coding/finalization-git";
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";
3
10
  import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
4
- import { asUnknownRecord } from "@leitwerk-dev/domain";
5
11
  import {
6
12
  type ForgejoGitIdentity,
7
13
  type ForgejoPullRequest,
8
14
  forgejoExternal,
9
15
  forgejoIssueWatcherSource,
10
16
  } from "@leitwerk-dev/forgejo";
11
- import { type FlowAutomaticRunContext, flow } from "@leitwerk-dev/process-sdk";
12
- import {
13
- type ConflictEvidence,
14
- conflictKey,
15
- validateConflict,
16
- } from "@leitwerk-dev/repository-rebase";
17
- import { publishRebase, startRebase } from "@leitwerk-dev/repository-rebase/git";
18
- import { rebasePrompt } from "@leitwerk-dev/repository-rebase/prompt";
19
- import { type WoodpeckerPipeline, woodpeckerExternal } from "@leitwerk-dev/woodpecker";
17
+ import type { FlowAutomaticRunContext } from "@leitwerk-dev/process-sdk";
18
+ import { woodpeckerExternal } from "@leitwerk-dev/woodpecker";
20
19
  import {
21
20
  type createForgejoRepoChangeLauncher,
22
21
  forgejoRepoChangeLaunchConfig,
@@ -35,102 +34,19 @@ const ids = {
35
34
  feedback: "revise_from_pull_request_feedback",
36
35
  ciRepair: "repair_woodpecker_pipeline",
37
36
  operator: "ci_operator_action",
38
- } as const;
39
-
40
- type FeedbackId = { kind: "conversation" | "review" | "inline"; id: number };
41
- type AdjustmentInvocation = {
42
- origin: "feedback" | "ci" | "rebase";
43
- publishRequired: boolean;
44
- };
45
-
46
- interface DeliveryState {
47
- stage: "not_started" | "branch_published" | "pull_request_ready" | "awaiting";
48
- issueLinked: boolean;
49
- adjustment: AdjustmentInvocation | null;
50
- terminalPullRequest: ForgejoPullRequest | null;
51
- }
52
-
53
- interface RemoteState {
54
- lastConflictKey?: string | null;
55
- conflict?: ConflictEvidence | null;
56
- repairReason?: "feedback" | "ci" | "rebase";
57
- headSha: string | null;
58
- prNumber: number | null;
59
- prUrl: string | null;
60
- conversationCursor: number;
61
- reviewCursor: number;
62
- inlineCursor: number;
63
- feedbackIds: FeedbackId[];
64
- pipeline: WoodpeckerPipeline | null;
65
- ciRecoveryCycles: number;
66
- delivery: DeliveryState;
67
- }
68
-
69
- const initialDeliveryState: DeliveryState = {
70
- stage: "not_started",
71
- issueLinked: false,
72
- adjustment: null,
73
- terminalPullRequest: null,
74
- };
75
-
76
- const initialRemoteState: RemoteState = {
77
- headSha: null,
78
- prNumber: null,
79
- prUrl: null,
80
- conversationCursor: 0,
81
- reviewCursor: 0,
82
- inlineCursor: 0,
83
- feedbackIds: [],
84
- pipeline: null,
85
- ciRecoveryCycles: 0,
86
- delivery: initialDeliveryState,
87
37
  };
88
-
89
- const object = (value: unknown) => asUnknownRecord(value) ?? {};
90
-
91
- function remote(state: RepositoryChangeState): RemoteState {
92
- const stored = object(object(state.extensionState).forgejoRepoChange);
93
- return {
94
- ...initialRemoteState,
95
- ...stored,
96
- delivery: {
97
- ...initialDeliveryState,
98
- ...object(stored.delivery),
99
- },
100
- } as RemoteState;
101
- }
102
-
103
- function patchRemote(
104
- state: RepositoryChangeState,
105
- patch: Partial<Omit<RemoteState, "delivery">> & { delivery?: Partial<DeliveryState> },
106
- ): RepositoryChangeState {
107
- const current = remote(state);
108
- return {
109
- ...state,
110
- extensionState: {
111
- ...state.extensionState,
112
- forgejoRepoChange: {
113
- ...current,
114
- ...patch,
115
- delivery: { ...current.delivery, ...patch.delivery },
116
- },
117
- },
118
- };
119
- }
120
-
38
+ const remote = (state: RepositoryChangeState) => readPublicationState(state, "forgejoRepoChange");
121
39
  function requirePr(state: RepositoryChangeState) {
122
40
  const value = remote(state);
123
- const { headSha, prNumber, prUrl } = value;
124
- if (!headSha || !prNumber || !prUrl) {
41
+ if (!value.headSha || !value.prNumber || !value.prUrl)
125
42
  throw new Error("Pull request delivery state is incomplete");
126
- }
127
- return { ...value, headSha, prNumber, prUrl };
128
- }
129
-
130
- function feedbackKey(value: FeedbackId): string {
131
- return `${value.kind}:${value.id}`;
43
+ return { ...value, headSha: value.headSha, prNumber: value.prNumber, prUrl: value.prUrl };
132
44
  }
133
-
45
+ const feedbackKey = (value: { kind: string; id: number }) => `${value.kind}:${value.id}`;
46
+ const callFor =
47
+ (ctx: PublicationContext<ForgejoRepoChangeParams>) =>
48
+ <T>(name: string, args: Record<string, unknown>) =>
49
+ ctx.callIntegrationTool(name, { projectKey: "repo", ...args }) as Promise<T>;
134
50
  function requireIssueOrigin(
135
51
  params: ForgejoRepoChangeParams,
136
52
  ): ForgejoRepoChangeParams & ForgejoIssueOriginParams {
@@ -159,70 +75,6 @@ function pinnedGitIdentity(
159
75
  return identity as unknown as ForgejoGitIdentity;
160
76
  }
161
77
 
162
- async function commitWorkBranch(
163
- ctx: FlowAutomaticRunContext<ForgejoRepoChangeParams, RepositoryChangeState>,
164
- commitMessage: string,
165
- ) {
166
- const repo = ctx.repo.get("repo");
167
- const gitIdentity =
168
- pinnedGitIdentity(ctx) ??
169
- ((await ctx.callIntegrationTool("forgejo_resolve_git_identity", {
170
- projectKey: "repo",
171
- })) as ForgejoGitIdentity);
172
- return commitAndPushWorkBranch({
173
- repoPath: repo.fsPath,
174
- workBranch: repo.workBranch,
175
- commitMessage,
176
- gitIdentity,
177
- });
178
- }
179
-
180
- function deliveryProgress(value: RemoteState, activeStepId?: string) {
181
- const delivery = value.delivery;
182
- const step = (id: string, label: string, done: boolean) => ({
183
- id,
184
- label,
185
- status: (activeStepId === id ? "in_progress" : done ? "completed" : "incomplete") as
186
- | "in_progress"
187
- | "completed"
188
- | "incomplete",
189
- });
190
- const adjustmentHandled =
191
- delivery.adjustment === null && delivery.stage === "awaiting" && value.headSha !== null;
192
- return {
193
- title: "Delivery progress",
194
- steps: [
195
- step("publish_branch", "Publish work branch", value.headSha !== null),
196
- step("open_pr", "Create or find pull request", value.prNumber !== null),
197
- step("link_issue", "Link source issue when applicable", delivery.issueLinked),
198
- step("publish_adjustment", "Publish an adjustment when applicable", adjustmentHandled),
199
- step(
200
- "reply_feedback",
201
- "Acknowledge or reply to feedback when applicable",
202
- value.feedbackIds.length === 0,
203
- ),
204
- step("await_evidence", "Await external evidence", delivery.stage === "awaiting"),
205
- step(
206
- "reconcile_terminal",
207
- "Reconcile terminal pull request",
208
- delivery.terminalPullRequest !== null,
209
- ),
210
- ],
211
- ...(value.prNumber && value.prUrl
212
- ? {
213
- links: [
214
- {
215
- id: `forgejo-pr-${value.prNumber}`,
216
- label: `Forgejo PR #${value.prNumber}`,
217
- url: value.prUrl,
218
- kind: "pull_request" as const,
219
- },
220
- ],
221
- }
222
- : {}),
223
- };
224
- }
225
-
226
78
  const deliveryTools = [
227
79
  "forgejo_get_pull_request",
228
80
  "forgejo_add_pull_request_comment",
@@ -241,10 +93,6 @@ export function createForgejoRepoChangeProcess(
241
93
  launcher: ReturnType<typeof createForgejoRepoChangeLauncher>,
242
94
  docker: boolean,
243
95
  ) {
244
- const publication = flow.fragment<ForgejoRepoChangeParams, RepositoryChangeState>(
245
- "forgejo-publication",
246
- );
247
-
248
96
  const failedPipeline = woodpeckerExternal.pipeline<
249
97
  ForgejoRepoChangeParams,
250
98
  RepositoryChangeState
@@ -262,193 +110,12 @@ export function createForgejoRepoChangeProcess(
262
110
  };
263
111
  });
264
112
 
265
- const delivery = flow
266
- .automatic<ForgejoRepoChangeParams, RepositoryChangeState>(ids.deliver)
267
- .description("Deliver")
268
- .integrationTools(...deliveryTools)
269
- .run(async (ctx) => {
270
- const call = <T>(name: string, args: Record<string, unknown>) =>
271
- ctx.callIntegrationTool(name, { projectKey: "repo", ...args }) as Promise<T>;
272
- let current = remote(ctx.state);
273
- const update = (patch: Parameters<typeof patchRemote>[1]) => {
274
- current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
275
- };
276
- const result = (outcome: "awaiting" | "feedback_ready" | "completed" | "aborted") => ({
277
- outcome,
278
- params: { nextState: patchRemote(ctx.state, current) },
279
- });
280
- ctx.reportProgress(deliveryProgress(current));
281
-
282
- if (current.delivery.terminalPullRequest) {
283
- ctx.reportProgress(deliveryProgress(current, "reconcile_terminal"));
284
- const pr = current.delivery.terminalPullRequest;
285
- if (isIssueOrigin(ctx.params)) {
286
- const issue = await call<{
287
- labels: Array<{ id: number; name: string }>;
288
- }>("forgejo_get_issue", {
289
- issueNumber: ctx.params.issueNumber,
290
- });
291
- let labels = issue.labels
292
- .filter((label) => label.name !== ctx.params.triggerLabel)
293
- .map((label) => label.id);
294
- if (pr.merged) {
295
- const done = await call<{ id: number }>("forgejo_ensure_label", {
296
- name: ctx.params.doneLabel,
297
- });
298
- labels = [...new Set([...labels, done.id])];
299
- }
300
- await call("forgejo_update_issue", {
301
- issueNumber: ctx.params.issueNumber,
302
- patch: { labels, ...(pr.merged ? { state: "closed" } : {}) },
303
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`,
304
- });
305
- await call("forgejo_add_issue_comment", {
306
- issueNumber: ctx.params.issueNumber,
307
- body: pr.merged
308
- ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.`
309
- : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
310
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`,
311
- });
312
- }
313
- ctx.reportProgress(deliveryProgress(current));
314
- return result(pr.merged ? "completed" : "aborted");
315
- }
316
-
317
- if (!current.headSha) {
318
- ctx.reportProgress(deliveryProgress(current, "publish_branch"));
319
- const published = await commitWorkBranch(
320
- ctx,
321
- ctx.state.finalization.generatedCommitMessage ?? "",
322
- );
323
- update({ headSha: published.headSha, pipeline: null });
324
- }
325
-
326
- if (!current.prNumber || !current.prUrl) {
327
- ctx.reportProgress(deliveryProgress(current, "open_pr"));
328
- const project = ctx.repo.get("repo");
329
- const issueOrigin = isIssueOrigin(ctx.params);
330
- const pr = await call<ForgejoPullRequest>("forgejo_ensure_pull_request", {
331
- title:
332
- ctx.process.title ??
333
- (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
334
- body: issueOrigin
335
- ? `Implements ${ctx.params.issueUrl}\n\nLeitwerk process: ${ctx.process.id}`
336
- : `Leitwerk process: ${ctx.process.id}`,
337
- head: project.workBranch,
338
- base: project.baseBranch,
339
- });
340
- if (!pr) throw new Error("Forgejo pull request could not be created or found");
341
- update({ prNumber: pr.number, prUrl: pr.html_url });
342
- }
343
-
344
- if (!current.delivery.issueLinked) {
345
- ctx.reportProgress(deliveryProgress(current, "link_issue"));
346
- if (isIssueOrigin(ctx.params)) {
347
- await call("forgejo_add_issue_comment", {
348
- issueNumber: ctx.params.issueNumber,
349
- body: `Leitwerk opened pull request ${current.prUrl}.`,
350
- writeKey: `forgejo:${ctx.process.id}:source-pr-link:${current.prNumber}`,
351
- });
352
- }
353
- update({ delivery: { issueLinked: true } });
354
- }
355
-
356
- if (current.delivery.adjustment) {
357
- const adjustment = current.delivery.adjustment;
358
- if (adjustment.publishRequired || adjustment.origin === "rebase") {
359
- ctx.reportProgress(deliveryProgress(current, "publish_adjustment"));
360
- const published =
361
- adjustment.origin === "rebase"
362
- ? publishRebase(rebaseInput(ctx))
363
- : await commitWorkBranch(
364
- ctx,
365
- adjustment.origin === "feedback"
366
- ? "fix: address Forgejo review feedback"
367
- : "fix: repair Woodpecker pipeline",
368
- );
369
- if (adjustment.origin === "rebase") {
370
- const refreshed = await call<ForgejoPullRequest>("forgejo_get_pull_request", {
371
- pullRequestNumber: current.prNumber,
372
- });
373
- if (refreshed.head.sha !== published.headSha)
374
- throw new Error("Pull request head has not caught up with rebase publication");
375
- }
376
- update({ headSha: published.headSha, pipeline: null });
377
- }
378
- if (adjustment.origin === "rebase")
379
- await call("forgejo_add_pull_request_comment", {
380
- pullRequestNumber: current.prNumber,
381
- body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
382
- writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`,
383
- });
384
- if (adjustment.origin === "feedback") {
385
- ctx.reportProgress(deliveryProgress(current, "reply_feedback"));
386
- for (const feedback of current.feedbackIds) {
387
- await call("forgejo_reply_to_pull_request_feedback", {
388
- pullRequestNumber: current.prNumber,
389
- feedbackKind: feedback.kind,
390
- feedbackId: feedback.id,
391
- body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
392
- writeKey: `forgejo:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`,
393
- });
394
- }
395
- }
396
- update({
397
- ...(adjustment.origin === "feedback" ? { feedbackIds: [] } : {}),
398
- delivery: { adjustment: null },
399
- });
400
- }
401
-
402
- if (current.feedbackIds.length > 0) {
403
- ctx.reportProgress(deliveryProgress(current, "reply_feedback"));
404
- for (const feedback of current.feedbackIds) {
405
- if (feedback.kind === "review") continue;
406
- await call("forgejo_add_pull_request_feedback_reaction", {
407
- pullRequestNumber: current.prNumber,
408
- feedbackKind: feedback.kind,
409
- feedbackId: feedback.id,
410
- writeKey: `forgejo:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`,
411
- });
412
- }
413
- return result("feedback_ready");
414
- }
415
-
416
- update({ delivery: { stage: "awaiting" } });
417
- ctx.reportProgress(deliveryProgress(current, "await_evidence"));
418
- return result("awaiting");
419
- })
420
- .outcome("awaiting", (outcome) =>
421
- outcome
422
- .description("Delivery is waiting for external evidence")
423
- .object("nextState")
424
- .wait()
425
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
426
- )
427
- .outcome("feedback_ready", (outcome) =>
428
- outcome
429
- .description("Pull request feedback is acknowledged and ready for revision")
430
- .object("nextState")
431
- .to(ids.feedback)
432
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
433
- )
434
- .outcome("completed", (outcome) =>
435
- outcome
436
- .description("Merged pull request was reconciled")
437
- .object("nextState")
438
- .complete()
439
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
440
- )
441
- .outcome("aborted", (outcome) =>
442
- outcome
443
- .description("Closed pull request was reconciled")
444
- .object("nextState")
445
- .lifecycleStatus("aborted")
446
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
447
- )
448
-
449
- .externalAction(
450
- "forgejo_merge_conflict",
451
- forgejoExternal.pullRequestConflict(({ params, state }) => ({
113
+ const sources: PublicationSource<ForgejoRepoChangeParams>[] = [
114
+ {
115
+ id: "forgejo_merge_conflict",
116
+ kind: "conflict",
117
+ label: "Rebase conflicting pull request",
118
+ source: forgejoExternal.pullRequestConflict(({ params, state }) => ({
452
119
  profile: params.forgejoProfile,
453
120
  owner: params.owner,
454
121
  repo: params.repo,
@@ -457,125 +124,75 @@ export function createForgejoRepoChangeProcess(
457
124
  lastConflictKey: remote(state).lastConflictKey,
458
125
  pollInterval: "30s",
459
126
  })),
460
- (external) =>
461
- external
462
- .label("Rebase conflicting pull request")
463
- .to(ids.feedback)
464
- .effect(({ params, state, event }) => {
465
- const current = requirePr(state);
466
- const conflict = validateConflict(
467
- object(event).conflict,
468
- {
469
- owner: params.owner,
470
- repo: params.repo,
471
- prNumber: current.prNumber,
472
- headSha: current.headSha,
473
- headBranch: params.workBranch,
474
- baseBranch: params.baseBranch,
475
- },
476
- current.lastConflictKey,
477
- );
478
- return {
479
- state: patchRemote(state, {
480
- lastConflictKey: conflictKey(conflict),
481
- conflict,
482
- repairReason: "rebase",
483
- }),
484
- };
485
- }),
486
- )
487
- .externalAction(
488
- "forgejo_feedback",
489
- forgejoExternal.pullRequestFeedback(({ params, state }) => {
490
- const current = requirePr(state);
491
- return {
492
- profile: params.forgejoProfile,
493
- owner: params.owner,
494
- repo: params.repo,
495
- prNumber: current.prNumber,
496
- conversationCursor: current.conversationCursor,
497
- reviewCursor: current.reviewCursor,
498
- inlineCursor: current.inlineCursor,
499
- quietPeriodMs: 120_000,
500
- pollInterval: "30s",
501
- };
127
+ read: ({ event }) => ({
128
+ kind: "conflict",
129
+ conflict: object(event).conflict as NonNullable<PublicationState["conflict"]>,
502
130
  }),
503
- (external) =>
504
- external
505
- .label("Forgejo pull request feedback")
506
- .to(ids.deliver)
507
- .effect(({ state, event }) => {
508
- const value = object(event);
509
- const cursors = object(value.cursors);
510
- return {
511
- state: patchRemote(state, {
512
- repairReason: "feedback",
513
- conversationCursor: Number(
514
- cursors.conversationCursor ?? remote(state).conversationCursor,
515
- ),
516
- reviewCursor: Number(cursors.reviewCursor ?? remote(state).reviewCursor),
517
- inlineCursor: Number(cursors.inlineCursor ?? remote(state).inlineCursor),
518
- feedbackIds: Array.isArray(value.feedbackIds)
519
- ? (value.feedbackIds as FeedbackId[])
520
- : [],
521
- }),
522
- };
523
- }),
524
- )
525
- .externalAction("woodpecker_failure_repair", failedPipeline, (external) =>
526
- external
527
- .label("Repair failed Woodpecker pipeline")
528
- .when(({ state }) => remote(state).ciRecoveryCycles < 3)
529
- .to(ids.ciRepair)
530
- .effect(({ state, event }) => ({
531
- state: patchRemote(state, {
532
- repairReason: "ci",
533
- pipeline: object(event).pipeline as WoodpeckerPipeline,
534
- ciRecoveryCycles: remote(state).ciRecoveryCycles + 1,
535
- }),
536
- })),
537
- )
538
- .externalAction("woodpecker_failure_operator", failedPipeline, (external) =>
539
- external
540
- .label("Escalate failed Woodpecker pipeline")
541
- .when(({ state }) => remote(state).ciRecoveryCycles >= 3)
542
- .to(ids.operator)
543
- .effect(({ state, event }) => ({
544
- state: patchRemote(state, {
545
- repairReason: "ci",
546
- pipeline: object(event).pipeline as WoodpeckerPipeline,
547
- }),
548
- })),
549
- );
550
- for (const [terminalOutcome, label] of [
551
- ["merged", "Forgejo pull request merged"],
552
- ["closed", "Forgejo pull request closed without merge"],
553
- ] as const) {
554
- delivery.externalAction(
555
- `forgejo_pr_${terminalOutcome}`,
556
- forgejoExternal.pullRequestTerminal(({ params, state }) => ({
131
+ },
132
+ {
133
+ id: "forgejo_feedback",
134
+ kind: "feedback",
135
+ label: "Forgejo pull request feedback",
136
+ source: forgejoExternal.pullRequestFeedback(({ params, state }) => ({
557
137
  profile: params.forgejoProfile,
558
138
  owner: params.owner,
559
139
  repo: params.repo,
560
140
  prNumber: requirePr(state).prNumber,
561
- terminalOutcome,
141
+ conversationCursor: remote(state).conversationCursor,
142
+ reviewCursor: remote(state).reviewCursor,
143
+ inlineCursor: remote(state).inlineCursor,
144
+ quietPeriodMs: 120000,
562
145
  pollInterval: "30s",
563
146
  })),
564
- (external) =>
565
- external
566
- .label(label)
567
- .to(ids.deliver)
568
- .effect(({ state, event }) => ({
569
- state: patchRemote(state, {
570
- delivery: { terminalPullRequest: object(event).pullRequest as ForgejoPullRequest },
571
- }),
572
- })),
573
- );
574
- }
575
- publication.turn(
576
- delivery.externalAction(
577
- "source_cancelled",
578
- forgejoExternal.issueCancelled(({ params }) => {
147
+ read: ({ state, event }) => {
148
+ const value = object(event);
149
+ const cursors = object(value.cursors);
150
+ const current = remote(state);
151
+ return {
152
+ kind: "feedback",
153
+ conversationCursor: Number(cursors.conversationCursor ?? current.conversationCursor),
154
+ reviewCursor: Number(cursors.reviewCursor ?? current.reviewCursor),
155
+ inlineCursor: Number(cursors.inlineCursor ?? current.inlineCursor),
156
+ feedbackIds: (value.feedbackIds ?? []) as PublicationState["feedbackIds"],
157
+ };
158
+ },
159
+ },
160
+ {
161
+ id: "woodpecker_failure_repair",
162
+ operatorId: "woodpecker_failure_operator",
163
+ kind: "failure",
164
+ label: "Repair failed Woodpecker pipeline",
165
+ source: failedPipeline,
166
+ read: ({ event }) => ({
167
+ kind: "failure",
168
+ pipeline: object(event).pipeline as NonNullable<PublicationState["pipeline"]>,
169
+ }),
170
+ },
171
+ ...(["merged", "closed"] as const).map((terminalOutcome) => ({
172
+ id: `forgejo_pr_${terminalOutcome}`,
173
+ kind: "terminal" as const,
174
+ label: `Forgejo pull request ${terminalOutcome}`,
175
+ source: forgejoExternal.pullRequestTerminal<ForgejoRepoChangeParams, RepositoryChangeState>(
176
+ ({ params, state }) => ({
177
+ profile: params.forgejoProfile,
178
+ owner: params.owner,
179
+ repo: params.repo,
180
+ prNumber: requirePr(state).prNumber,
181
+ terminalOutcome,
182
+ pollInterval: "30s",
183
+ }),
184
+ ),
185
+ read: ({ event }: { event: unknown }) => ({
186
+ kind: "terminal" as const,
187
+ request: object(event).pullRequest as ForgejoPullRequest,
188
+ }),
189
+ })),
190
+ {
191
+ id: "source_cancelled",
192
+ kind: "cancelled",
193
+ label: "Source issue cancelled",
194
+ enabled: isIssueOrigin,
195
+ source: forgejoExternal.issueCancelled(({ params }) => {
579
196
  const issue = requireIssueOrigin(params);
580
197
  return {
581
198
  profile: issue.forgejoProfile,
@@ -586,117 +203,138 @@ export function createForgejoRepoChangeProcess(
586
203
  pollInterval: "30s",
587
204
  };
588
205
  }),
589
- (external) =>
590
- external
591
- .label("Source issue cancelled")
592
- .when(({ params }) => isIssueOrigin(params))
593
- .lifecycleStatus("aborted"),
594
- ),
595
- );
596
-
597
- function rebaseInput(ctx: {
598
- state: RepositoryChangeState;
599
- repo: { get(key: string): { fsPath: string; workBranch: string } };
600
- }) {
601
- const project = ctx.repo.get("repo");
602
- const conflict = remote(ctx.state).conflict;
603
- if (!conflict) throw new Error("Missing conflict evidence");
604
- return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
605
- }
606
- function repairReason(state: RepositoryChangeState, kind: "feedback" | "ci") {
607
- return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
608
- }
609
-
610
- function revisionPrompt(kind: "feedback" | "ci") {
611
- return (ctx: { state: RepositoryChangeState }) => {
612
- const current = remote(ctx.state);
613
- if (repairReason(ctx.state, kind) === "rebase")
614
- return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
206
+ read: () => ({ kind: "cancelled" }),
207
+ },
208
+ ];
209
+ const publicationConfig = createRepositoryChangePublication<ForgejoRepoChangeParams>({
210
+ namespace: "forgejoRepoChange",
211
+ label: "Forgejo PR",
212
+ ids,
213
+ sources,
214
+ tools: {
215
+ delivery: deliveryTools,
216
+ feedback: ["forgejo_get_pull_request", "forgejo_list_pull_request_feedback"],
217
+ ci: [
218
+ "woodpecker_lookup_repository",
219
+ "woodpecker_list_pipelines",
220
+ "woodpecker_get_pipeline",
221
+ "woodpecker_get_step_logs",
222
+ "woodpecker_restart_pipeline",
223
+ ],
224
+ },
225
+ async identity(ctx) {
226
+ return (
227
+ pinnedGitIdentity(ctx) ??
228
+ (await callFor(ctx)<ForgejoGitIdentity>("forgejo_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<{ id: number; name: string }>;
236
+ }>("forgejo_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.id);
242
+ if (pr.merged) {
243
+ const done = await call<{ id: number }>("forgejo_ensure_label", {
244
+ name: ctx.params.doneLabel,
245
+ });
246
+ labels = [...new Set([...labels, done.id])];
247
+ }
248
+ await call("forgejo_update_issue", {
249
+ issueNumber: ctx.params.issueNumber,
250
+ patch: { labels, ...(pr.merged ? { state: "closed" } : {}) },
251
+ writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`,
252
+ });
253
+ await call("forgejo_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: `forgejo:${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<ForgejoPullRequest>("forgejo_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("Forgejo 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("forgejo_add_issue_comment", {
283
+ issueNumber: ctx.params.issueNumber,
284
+ body: `Leitwerk opened pull request ${current.prUrl}.`,
285
+ writeKey: `forgejo:${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("forgejo_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: `forgejo:${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("forgejo_add_pull_request_feedback_reaction", {
306
+ pullRequestNumber: current.prNumber,
307
+ feedbackKind: feedback.kind,
308
+ feedbackId: feedback.id,
309
+ writeKey: `forgejo:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`,
310
+ });
311
+ }
312
+ },
313
+ async head(ctx, current) {
314
+ return (
315
+ await callFor(ctx)<ForgejoPullRequest>("forgejo_get_pull_request", {
316
+ pullRequestNumber: current.prNumber,
317
+ })
318
+ ).head.sha;
319
+ },
320
+ async afterRebase(ctx, current) {
321
+ await callFor(ctx)("forgejo_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"
329
+ ? "fix: address Forgejo review feedback"
330
+ : "fix: repair Woodpecker pipeline",
331
+ prompt(kind, current) {
615
332
  return kind === "feedback"
616
333
  ? `Address the unseen Forgejo pull-request feedback batch for PR #${current.prNumber}. Feedback identifiers: ${JSON.stringify(current.feedbackIds)}. Inspect the current checkout and use Forgejo 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.`
617
334
  : `Diagnose Woodpecker pipeline #${current.pipeline?.number ?? "unknown"} (${current.pipeline?.status ?? "unknown"}) for the current checkout. Use Woodpecker tools to inspect pipeline metadata and bounded failed-step 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.`;
618
- };
619
- }
620
-
621
- function revisionTurn(id: string, kind: "feedback" | "ci") {
622
- const turn = flow
623
- .llm<ForgejoRepoChangeParams, RepositoryChangeState>(id)
624
- .description(kind === "feedback" ? "Address Feedback" : "Fix CI")
625
- .tools("read", "bash", "edit", "write")
626
- .resolveIntegrationTools((_params, state) =>
627
- repairReason(state, kind) === "rebase"
628
- ? []
629
- : kind === "feedback"
630
- ? ["forgejo_get_pull_request", "forgejo_list_pull_request_feedback"]
631
- : [
632
- "woodpecker_lookup_repository",
633
- "woodpecker_list_pipelines",
634
- "woodpecker_get_pipeline",
635
- "woodpecker_get_step_logs",
636
- "woodpecker_restart_pipeline",
637
- ],
638
- )
639
- .prepare((ctx) =>
640
- repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {},
641
- )
642
- .freshPrimary()
643
- .prompt(revisionPrompt(kind));
644
- for (const [name, description, publishRequired] of [
645
- ["changes_ready", "Repository changes are ready to publish", true],
646
- ["no_changes", "No repository change is required", false],
647
- ] as const) {
648
- turn.outcomeTool(name, (tool) =>
649
- tool
650
- .resultSummary()
651
- .description(description)
652
- .to(ids.deliver)
653
- .state(({ ctx }) =>
654
- patchRemote(ctx.state, {
655
- delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } },
656
- }),
657
- ),
658
- );
659
- }
660
- return turn.outcomeTool("cannot_repair", (tool) =>
661
- tool.description("The adjustment requires operator action").to(ids.operator),
662
- );
663
- }
664
-
665
- publication.turn(revisionTurn(ids.feedback, "feedback"));
666
- publication.turn(revisionTurn(ids.ciRepair, "ci"));
667
- publication.turn({
668
- id: ids.operator,
669
- definition: {
670
- kind: "human",
671
- description: "Repository repair needs operator action",
672
- operatorAttention: "required",
673
- actions: {
674
- retry_repair: {
675
- label: "Retry repair",
676
- acceptanceState: "accepted",
677
- branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
678
- choose: ({ ctx }) =>
679
- remote(ctx.state).repairReason === "rebase" ||
680
- remote(ctx.state).repairReason === "feedback"
681
- ? "feedback"
682
- : "ci",
683
- },
684
- resume_waiting: {
685
- label: "Resume waiting",
686
- acceptanceState: "accepted",
687
- to: ids.deliver,
688
- effect: ({ ctx }) => ({
689
- state: patchRemote(ctx.state, {
690
- feedbackIds: [],
691
- delivery: { adjustment: null },
692
- }),
693
- }),
694
- },
695
- abort: { label: "Abort process", acceptanceState: "neutral", lifecycleStatus: "aborted" },
696
- },
697
335
  },
698
336
  });
699
-
337
+ const publication = publicationConfig.fragment;
700
338
  publication.watcher({
701
339
  id: "use_leitwerk",
702
340
  label: "Forgejo use-leitwerk issues",
@@ -739,7 +377,6 @@ export function createForgejoRepoChangeProcess(
739
377
  fields: [],
740
378
  submitLabel: "Publish",
741
379
  },
742
- finalizationDescription: "Publish feature branch",
743
380
  repositoryCredentials: ({ params }) => [
744
381
  {
745
382
  projectKey: "repo",
@@ -747,11 +384,7 @@ export function createForgejoRepoChangeProcess(
747
384
  credentialRef: params.sshCredentialRef,
748
385
  },
749
386
  ],
750
- publication: {
751
- entryTurnId: ids.deliver,
752
- fragment: publication,
753
- happyPath: [ids.deliver],
754
- },
387
+ publication: publicationConfig,
755
388
  });
756
389
 
757
390
  definition.process.runtime = { ...definition.process.runtime, docker };