@leitwerk-dev/forgejo-repo-change 0.2.0 → 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",
@@ -236,14 +88,11 @@ const deliveryTools = [
236
88
  "forgejo_update_issue",
237
89
  ] as const;
238
90
 
91
+ /** @internal */
239
92
  export function createForgejoRepoChangeProcess(
240
93
  launcher: ReturnType<typeof createForgejoRepoChangeLauncher>,
241
94
  docker: boolean,
242
95
  ) {
243
- const publication = flow.fragment<ForgejoRepoChangeParams, RepositoryChangeState>(
244
- "forgejo-publication",
245
- );
246
-
247
96
  const failedPipeline = woodpeckerExternal.pipeline<
248
97
  ForgejoRepoChangeParams,
249
98
  RepositoryChangeState
@@ -261,193 +110,12 @@ export function createForgejoRepoChangeProcess(
261
110
  };
262
111
  });
263
112
 
264
- const delivery = flow
265
- .automatic<ForgejoRepoChangeParams, RepositoryChangeState>(ids.deliver)
266
- .description("Deliver")
267
- .integrationTools(...deliveryTools)
268
- .run(async (ctx) => {
269
- const call = <T>(name: string, args: Record<string, unknown>) =>
270
- ctx.callIntegrationTool(name, { projectKey: "repo", ...args }) as Promise<T>;
271
- let current = remote(ctx.state);
272
- const update = (patch: Parameters<typeof patchRemote>[1]) => {
273
- current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
274
- };
275
- const result = (outcome: "awaiting" | "feedback_ready" | "completed" | "aborted") => ({
276
- outcome,
277
- params: { nextState: patchRemote(ctx.state, current) },
278
- });
279
- ctx.reportProgress(deliveryProgress(current));
280
-
281
- if (current.delivery.terminalPullRequest) {
282
- ctx.reportProgress(deliveryProgress(current, "reconcile_terminal"));
283
- const pr = current.delivery.terminalPullRequest;
284
- if (isIssueOrigin(ctx.params)) {
285
- const issue = await call<{
286
- labels: Array<{ id: number; name: string }>;
287
- }>("forgejo_get_issue", {
288
- issueNumber: ctx.params.issueNumber,
289
- });
290
- let labels = issue.labels
291
- .filter((label) => label.name !== ctx.params.triggerLabel)
292
- .map((label) => label.id);
293
- if (pr.merged) {
294
- const done = await call<{ id: number }>("forgejo_ensure_label", {
295
- name: ctx.params.doneLabel,
296
- });
297
- labels = [...new Set([...labels, done.id])];
298
- }
299
- await call("forgejo_update_issue", {
300
- issueNumber: ctx.params.issueNumber,
301
- patch: { labels, ...(pr.merged ? { state: "closed" } : {}) },
302
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`,
303
- });
304
- await call("forgejo_add_issue_comment", {
305
- issueNumber: ctx.params.issueNumber,
306
- body: pr.merged
307
- ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.`
308
- : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
309
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`,
310
- });
311
- }
312
- ctx.reportProgress(deliveryProgress(current));
313
- return result(pr.merged ? "completed" : "aborted");
314
- }
315
-
316
- if (!current.headSha) {
317
- ctx.reportProgress(deliveryProgress(current, "publish_branch"));
318
- const published = await commitWorkBranch(
319
- ctx,
320
- ctx.state.finalization.generatedCommitMessage ?? "",
321
- );
322
- update({ headSha: published.headSha, pipeline: null });
323
- }
324
-
325
- if (!current.prNumber || !current.prUrl) {
326
- ctx.reportProgress(deliveryProgress(current, "open_pr"));
327
- const project = ctx.repo.get("repo");
328
- const issueOrigin = isIssueOrigin(ctx.params);
329
- const pr = await call<ForgejoPullRequest>("forgejo_ensure_pull_request", {
330
- title:
331
- ctx.process.title ??
332
- (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
333
- body: issueOrigin
334
- ? `Implements ${ctx.params.issueUrl}\n\nLeitwerk process: ${ctx.process.id}`
335
- : `Leitwerk process: ${ctx.process.id}`,
336
- head: project.workBranch,
337
- base: project.baseBranch,
338
- });
339
- if (!pr) throw new Error("Forgejo pull request could not be created or found");
340
- update({ prNumber: pr.number, prUrl: pr.html_url });
341
- }
342
-
343
- if (!current.delivery.issueLinked) {
344
- ctx.reportProgress(deliveryProgress(current, "link_issue"));
345
- if (isIssueOrigin(ctx.params)) {
346
- await call("forgejo_add_issue_comment", {
347
- issueNumber: ctx.params.issueNumber,
348
- body: `Leitwerk opened pull request ${current.prUrl}.`,
349
- writeKey: `forgejo:${ctx.process.id}:source-pr-link:${current.prNumber}`,
350
- });
351
- }
352
- update({ delivery: { issueLinked: true } });
353
- }
354
-
355
- if (current.delivery.adjustment) {
356
- const adjustment = current.delivery.adjustment;
357
- if (adjustment.publishRequired || adjustment.origin === "rebase") {
358
- ctx.reportProgress(deliveryProgress(current, "publish_adjustment"));
359
- const published =
360
- adjustment.origin === "rebase"
361
- ? publishRebase(rebaseInput(ctx))
362
- : await commitWorkBranch(
363
- ctx,
364
- adjustment.origin === "feedback"
365
- ? "fix: address Forgejo review feedback"
366
- : "fix: repair Woodpecker pipeline",
367
- );
368
- if (adjustment.origin === "rebase") {
369
- const refreshed = await call<ForgejoPullRequest>("forgejo_get_pull_request", {
370
- pullRequestNumber: current.prNumber,
371
- });
372
- if (refreshed.head.sha !== published.headSha)
373
- throw new Error("Pull request head has not caught up with rebase publication");
374
- }
375
- update({ headSha: published.headSha, pipeline: null });
376
- }
377
- if (adjustment.origin === "rebase")
378
- await call("forgejo_add_pull_request_comment", {
379
- pullRequestNumber: current.prNumber,
380
- body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
381
- writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`,
382
- });
383
- if (adjustment.origin === "feedback") {
384
- ctx.reportProgress(deliveryProgress(current, "reply_feedback"));
385
- for (const feedback of current.feedbackIds) {
386
- await call("forgejo_reply_to_pull_request_feedback", {
387
- pullRequestNumber: current.prNumber,
388
- feedbackKind: feedback.kind,
389
- feedbackId: feedback.id,
390
- body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
391
- writeKey: `forgejo:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`,
392
- });
393
- }
394
- }
395
- update({
396
- ...(adjustment.origin === "feedback" ? { feedbackIds: [] } : {}),
397
- delivery: { adjustment: null },
398
- });
399
- }
400
-
401
- if (current.feedbackIds.length > 0) {
402
- ctx.reportProgress(deliveryProgress(current, "reply_feedback"));
403
- for (const feedback of current.feedbackIds) {
404
- if (feedback.kind === "review") continue;
405
- await call("forgejo_add_pull_request_feedback_reaction", {
406
- pullRequestNumber: current.prNumber,
407
- feedbackKind: feedback.kind,
408
- feedbackId: feedback.id,
409
- writeKey: `forgejo:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`,
410
- });
411
- }
412
- return result("feedback_ready");
413
- }
414
-
415
- update({ delivery: { stage: "awaiting" } });
416
- ctx.reportProgress(deliveryProgress(current, "await_evidence"));
417
- return result("awaiting");
418
- })
419
- .outcome("awaiting", (outcome) =>
420
- outcome
421
- .description("Delivery is waiting for external evidence")
422
- .object("nextState")
423
- .wait()
424
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
425
- )
426
- .outcome("feedback_ready", (outcome) =>
427
- outcome
428
- .description("Pull request feedback is acknowledged and ready for revision")
429
- .object("nextState")
430
- .to(ids.feedback)
431
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
432
- )
433
- .outcome("completed", (outcome) =>
434
- outcome
435
- .description("Merged pull request was reconciled")
436
- .object("nextState")
437
- .complete()
438
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
439
- )
440
- .outcome("aborted", (outcome) =>
441
- outcome
442
- .description("Closed pull request was reconciled")
443
- .object("nextState")
444
- .lifecycleStatus("aborted")
445
- .state(({ event }) => event.params.nextState as RepositoryChangeState),
446
- )
447
-
448
- .externalAction(
449
- "forgejo_merge_conflict",
450
- 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 }) => ({
451
119
  profile: params.forgejoProfile,
452
120
  owner: params.owner,
453
121
  repo: params.repo,
@@ -456,125 +124,75 @@ export function createForgejoRepoChangeProcess(
456
124
  lastConflictKey: remote(state).lastConflictKey,
457
125
  pollInterval: "30s",
458
126
  })),
459
- (external) =>
460
- external
461
- .label("Rebase conflicting pull request")
462
- .to(ids.feedback)
463
- .effect(({ params, state, event }) => {
464
- const current = requirePr(state);
465
- const conflict = validateConflict(
466
- object(event).conflict,
467
- {
468
- owner: params.owner,
469
- repo: params.repo,
470
- prNumber: current.prNumber,
471
- headSha: current.headSha,
472
- headBranch: params.workBranch,
473
- baseBranch: params.baseBranch,
474
- },
475
- current.lastConflictKey,
476
- );
477
- return {
478
- state: patchRemote(state, {
479
- lastConflictKey: conflictKey(conflict),
480
- conflict,
481
- repairReason: "rebase",
482
- }),
483
- };
484
- }),
485
- )
486
- .externalAction(
487
- "forgejo_feedback",
488
- forgejoExternal.pullRequestFeedback(({ params, state }) => {
489
- const current = requirePr(state);
490
- return {
491
- profile: params.forgejoProfile,
492
- owner: params.owner,
493
- repo: params.repo,
494
- prNumber: current.prNumber,
495
- conversationCursor: current.conversationCursor,
496
- reviewCursor: current.reviewCursor,
497
- inlineCursor: current.inlineCursor,
498
- quietPeriodMs: 120_000,
499
- pollInterval: "30s",
500
- };
127
+ read: ({ event }) => ({
128
+ kind: "conflict",
129
+ conflict: object(event).conflict as NonNullable<PublicationState["conflict"]>,
501
130
  }),
502
- (external) =>
503
- external
504
- .label("Forgejo pull request feedback")
505
- .to(ids.deliver)
506
- .effect(({ state, event }) => {
507
- const value = object(event);
508
- const cursors = object(value.cursors);
509
- return {
510
- state: patchRemote(state, {
511
- repairReason: "feedback",
512
- conversationCursor: Number(
513
- cursors.conversationCursor ?? remote(state).conversationCursor,
514
- ),
515
- reviewCursor: Number(cursors.reviewCursor ?? remote(state).reviewCursor),
516
- inlineCursor: Number(cursors.inlineCursor ?? remote(state).inlineCursor),
517
- feedbackIds: Array.isArray(value.feedbackIds)
518
- ? (value.feedbackIds as FeedbackId[])
519
- : [],
520
- }),
521
- };
522
- }),
523
- )
524
- .externalAction("woodpecker_failure_repair", failedPipeline, (external) =>
525
- external
526
- .label("Repair failed Woodpecker pipeline")
527
- .when(({ state }) => remote(state).ciRecoveryCycles < 3)
528
- .to(ids.ciRepair)
529
- .effect(({ state, event }) => ({
530
- state: patchRemote(state, {
531
- repairReason: "ci",
532
- pipeline: object(event).pipeline as WoodpeckerPipeline,
533
- ciRecoveryCycles: remote(state).ciRecoveryCycles + 1,
534
- }),
535
- })),
536
- )
537
- .externalAction("woodpecker_failure_operator", failedPipeline, (external) =>
538
- external
539
- .label("Escalate failed Woodpecker pipeline")
540
- .when(({ state }) => remote(state).ciRecoveryCycles >= 3)
541
- .to(ids.operator)
542
- .effect(({ state, event }) => ({
543
- state: patchRemote(state, {
544
- repairReason: "ci",
545
- pipeline: object(event).pipeline as WoodpeckerPipeline,
546
- }),
547
- })),
548
- );
549
- for (const [terminalOutcome, label] of [
550
- ["merged", "Forgejo pull request merged"],
551
- ["closed", "Forgejo pull request closed without merge"],
552
- ] as const) {
553
- delivery.externalAction(
554
- `forgejo_pr_${terminalOutcome}`,
555
- 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 }) => ({
556
137
  profile: params.forgejoProfile,
557
138
  owner: params.owner,
558
139
  repo: params.repo,
559
140
  prNumber: requirePr(state).prNumber,
560
- terminalOutcome,
141
+ conversationCursor: remote(state).conversationCursor,
142
+ reviewCursor: remote(state).reviewCursor,
143
+ inlineCursor: remote(state).inlineCursor,
144
+ quietPeriodMs: 120000,
561
145
  pollInterval: "30s",
562
146
  })),
563
- (external) =>
564
- external
565
- .label(label)
566
- .to(ids.deliver)
567
- .effect(({ state, event }) => ({
568
- state: patchRemote(state, {
569
- delivery: { terminalPullRequest: object(event).pullRequest as ForgejoPullRequest },
570
- }),
571
- })),
572
- );
573
- }
574
- publication.turn(
575
- delivery.externalAction(
576
- "source_cancelled",
577
- 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 }) => {
578
196
  const issue = requireIssueOrigin(params);
579
197
  return {
580
198
  profile: issue.forgejoProfile,
@@ -585,117 +203,138 @@ export function createForgejoRepoChangeProcess(
585
203
  pollInterval: "30s",
586
204
  };
587
205
  }),
588
- (external) =>
589
- external
590
- .label("Source issue cancelled")
591
- .when(({ params }) => isIssueOrigin(params))
592
- .lifecycleStatus("aborted"),
593
- ),
594
- );
595
-
596
- function rebaseInput(ctx: {
597
- state: RepositoryChangeState;
598
- repo: { get(key: string): { fsPath: string; workBranch: string } };
599
- }) {
600
- const project = ctx.repo.get("repo");
601
- const conflict = remote(ctx.state).conflict;
602
- if (!conflict) throw new Error("Missing conflict evidence");
603
- return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
604
- }
605
- function repairReason(state: RepositoryChangeState, kind: "feedback" | "ci") {
606
- return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
607
- }
608
-
609
- function revisionPrompt(kind: "feedback" | "ci") {
610
- return (ctx: { state: RepositoryChangeState }) => {
611
- const current = remote(ctx.state);
612
- if (repairReason(ctx.state, kind) === "rebase")
613
- 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) {
614
332
  return kind === "feedback"
615
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.`
616
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.`;
617
- };
618
- }
619
-
620
- function revisionTurn(id: string, kind: "feedback" | "ci") {
621
- const turn = flow
622
- .llm<ForgejoRepoChangeParams, RepositoryChangeState>(id)
623
- .description(kind === "feedback" ? "Address Feedback" : "Fix CI")
624
- .tools("read", "bash", "edit", "write")
625
- .resolveIntegrationTools((_params, state) =>
626
- repairReason(state, kind) === "rebase"
627
- ? []
628
- : kind === "feedback"
629
- ? ["forgejo_get_pull_request", "forgejo_list_pull_request_feedback"]
630
- : [
631
- "woodpecker_lookup_repository",
632
- "woodpecker_list_pipelines",
633
- "woodpecker_get_pipeline",
634
- "woodpecker_get_step_logs",
635
- "woodpecker_restart_pipeline",
636
- ],
637
- )
638
- .prepare((ctx) =>
639
- repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {},
640
- )
641
- .freshPrimary()
642
- .prompt(revisionPrompt(kind));
643
- for (const [name, description, publishRequired] of [
644
- ["changes_ready", "Repository changes are ready to publish", true],
645
- ["no_changes", "No repository change is required", false],
646
- ] as const) {
647
- turn.outcomeTool(name, (tool) =>
648
- tool
649
- .resultSummary()
650
- .description(description)
651
- .to(ids.deliver)
652
- .state(({ ctx }) =>
653
- patchRemote(ctx.state, {
654
- delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } },
655
- }),
656
- ),
657
- );
658
- }
659
- return turn.outcomeTool("cannot_repair", (tool) =>
660
- tool.description("The adjustment requires operator action").to(ids.operator),
661
- );
662
- }
663
-
664
- publication.turn(revisionTurn(ids.feedback, "feedback"));
665
- publication.turn(revisionTurn(ids.ciRepair, "ci"));
666
- publication.turn({
667
- id: ids.operator,
668
- definition: {
669
- kind: "human",
670
- description: "Repository repair needs operator action",
671
- operatorAttention: "required",
672
- actions: {
673
- retry_repair: {
674
- label: "Retry repair",
675
- acceptanceState: "accepted",
676
- branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
677
- choose: ({ ctx }) =>
678
- remote(ctx.state).repairReason === "rebase" ||
679
- remote(ctx.state).repairReason === "feedback"
680
- ? "feedback"
681
- : "ci",
682
- },
683
- resume_waiting: {
684
- label: "Resume waiting",
685
- acceptanceState: "accepted",
686
- to: ids.deliver,
687
- effect: ({ ctx }) => ({
688
- state: patchRemote(ctx.state, {
689
- feedbackIds: [],
690
- delivery: { adjustment: null },
691
- }),
692
- }),
693
- },
694
- abort: { label: "Abort process", acceptanceState: "neutral", lifecycleStatus: "aborted" },
695
- },
696
335
  },
697
336
  });
698
-
337
+ const publication = publicationConfig.fragment;
699
338
  publication.watcher({
700
339
  id: "use_leitwerk",
701
340
  label: "Forgejo use-leitwerk issues",
@@ -738,7 +377,6 @@ export function createForgejoRepoChangeProcess(
738
377
  fields: [],
739
378
  submitLabel: "Publish",
740
379
  },
741
- finalizationDescription: "Publish feature branch",
742
380
  repositoryCredentials: ({ params }) => [
743
381
  {
744
382
  projectKey: "repo",
@@ -746,11 +384,7 @@ export function createForgejoRepoChangeProcess(
746
384
  credentialRef: params.sshCredentialRef,
747
385
  },
748
386
  ],
749
- publication: {
750
- entryTurnId: ids.deliver,
751
- fragment: publication,
752
- happyPath: [ids.deliver],
753
- },
387
+ publication: publicationConfig,
754
388
  });
755
389
 
756
390
  definition.process.runtime = { ...definition.process.runtime, docker };