@leitwerk-dev/forgejo-repo-change 0.2.1 → 0.3.1

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,29 +1,20 @@
1
1
  import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
2
- import { commitAndPushWorkBranch } from "@leitwerk-dev/coding/finalization-git";
3
- import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
4
- import { asUnknownRecord } from "@leitwerk-dev/domain";
5
- import {
6
- type ForgejoGitIdentity,
7
- type ForgejoPullRequest,
8
- forgejoExternal,
9
- forgejoIssueWatcherSource,
10
- } 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";
20
2
  import {
21
- type createForgejoRepoChangeLauncher,
22
- forgejoRepoChangeLaunchConfig,
23
- forgejoRepoChangeParams,
24
- } from "./launcher.js";
3
+ createRepositoryChangePublication,
4
+ publicationObject as object,
5
+ type PublicationSource,
6
+ type PublicationState,
7
+ pullRequestPublicationCallbacks,
8
+ pullRequestPublicationSources,
9
+ readPublicationState,
10
+ reconcilePullRequestSourceIssue,
11
+ resolvePullRequestGitIdentity,
12
+ } from "@leitwerk-dev/coding/repository-change-publication";
13
+ import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
14
+ import { forgejoExternal, forgejoIssueWatcherSource } from "@leitwerk-dev/forgejo";
15
+ import { woodpeckerExternal } from "@leitwerk-dev/woodpecker";
16
+ import type { createForgejoRepoChangeLauncher } from "./launcher.js";
25
17
  import {
26
- type ForgejoIssueOriginParams,
27
18
  type ForgejoRepoChangeParams,
28
19
  forgejoRepoChangeParamsCodec,
29
20
  isIssueOrigin,
@@ -35,193 +26,8 @@ const ids = {
35
26
  feedback: "revise_from_pull_request_feedback",
36
27
  ciRepair: "repair_woodpecker_pipeline",
37
28
  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
29
  };
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
- };
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
-
121
- function requirePr(state: RepositoryChangeState) {
122
- const value = remote(state);
123
- const { headSha, prNumber, prUrl } = value;
124
- if (!headSha || !prNumber || !prUrl) {
125
- 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}`;
132
- }
133
-
134
- function requireIssueOrigin(
135
- params: ForgejoRepoChangeParams,
136
- ): ForgejoRepoChangeParams & ForgejoIssueOriginParams {
137
- if (!isIssueOrigin(params)) throw new Error("Forgejo source issue metadata is unavailable");
138
- return params;
139
- }
140
-
141
- function pinnedGitIdentity(
142
- ctx: FlowAutomaticRunContext<ForgejoRepoChangeParams, RepositoryChangeState>,
143
- ): ForgejoGitIdentity | null {
144
- const project = ctx.projects.find((candidate) => candidate.key === "repo");
145
- const candidate = object(project?.metadata)?.["leitwerk.gitIdentity"];
146
- const identity = object(candidate);
147
- if (
148
- identity.provider !== "forgejo" ||
149
- identity.profile !== ctx.params.forgejoProfile ||
150
- typeof identity.login !== "string" ||
151
- !identity.login.trim() ||
152
- typeof identity.name !== "string" ||
153
- !identity.name.trim() ||
154
- typeof identity.email !== "string" ||
155
- !identity.email.trim()
156
- ) {
157
- return null;
158
- }
159
- return identity as unknown as ForgejoGitIdentity;
160
- }
161
-
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
- }
30
+ const remote = (state: RepositoryChangeState) => readPublicationState(state, "forgejoRepoChange");
225
31
 
226
32
  const deliveryTools = [
227
33
  "forgejo_get_pull_request",
@@ -241,10 +47,14 @@ export function createForgejoRepoChangeProcess(
241
47
  launcher: ReturnType<typeof createForgejoRepoChangeLauncher>,
242
48
  docker: boolean,
243
49
  ) {
244
- const publication = flow.fragment<ForgejoRepoChangeParams, RepositoryChangeState>(
245
- "forgejo-publication",
50
+ const sharedSources = pullRequestPublicationSources<ForgejoRepoChangeParams>(
51
+ "forgejo",
52
+ "Forgejo",
53
+ forgejoExternal,
54
+ (params) => params.forgejoProfile,
55
+ (params) => (isIssueOrigin(params) ? params : undefined),
246
56
  );
247
-
57
+ const { requirePr } = sharedSources;
248
58
  const failedPipeline = woodpeckerExternal.pipeline<
249
59
  ForgejoRepoChangeParams,
250
60
  RepositoryChangeState
@@ -262,193 +72,12 @@ export function createForgejoRepoChangeProcess(
262
72
  };
263
73
  });
264
74
 
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 }) => ({
75
+ const sources: PublicationSource<ForgejoRepoChangeParams>[] = [
76
+ {
77
+ id: "forgejo_merge_conflict",
78
+ kind: "conflict",
79
+ label: "Rebase conflicting pull request",
80
+ source: forgejoExternal.pullRequestConflict(({ params, state }) => ({
452
81
  profile: params.forgejoProfile,
453
82
  owner: params.owner,
454
83
  repo: params.repo,
@@ -457,274 +86,69 @@ export function createForgejoRepoChangeProcess(
457
86
  lastConflictKey: remote(state).lastConflictKey,
458
87
  pollInterval: "30s",
459
88
  })),
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
- };
89
+ read: ({ event }) => ({
90
+ kind: "conflict",
91
+ conflict: object(event).conflict as NonNullable<PublicationState["conflict"]>,
502
92
  }),
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 }) => ({
557
- profile: params.forgejoProfile,
558
- owner: params.owner,
559
- repo: params.repo,
560
- prNumber: requirePr(state).prNumber,
561
- terminalOutcome,
562
- pollInterval: "30s",
563
- })),
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 }) => {
579
- const issue = requireIssueOrigin(params);
580
- return {
581
- profile: issue.forgejoProfile,
582
- owner: issue.owner,
583
- repo: issue.repo,
584
- issueNumber: issue.issueNumber,
585
- triggerLabel: issue.triggerLabel,
586
- pollInterval: "30s",
587
- };
93
+ },
94
+ sharedSources.feedback,
95
+ {
96
+ id: "woodpecker_failure_repair",
97
+ operatorId: "woodpecker_failure_operator",
98
+ kind: "failure",
99
+ label: "Repair failed Woodpecker pipeline",
100
+ source: failedPipeline,
101
+ read: ({ event }) => ({
102
+ kind: "failure",
103
+ pipeline: object(event).pipeline as NonNullable<PublicationState["pipeline"]>,
588
104
  }),
589
- (external) =>
590
- external
591
- .label("Source issue cancelled")
592
- .when(({ params }) => isIssueOrigin(params))
593
- .lifecycleStatus("aborted"),
105
+ },
106
+ ...sharedSources.terminal,
107
+ sharedSources.cancelled,
108
+ ];
109
+ const publicationConfig = createRepositoryChangePublication<ForgejoRepoChangeParams>({
110
+ namespace: "forgejoRepoChange",
111
+ label: "Forgejo PR",
112
+ ids,
113
+ sources,
114
+ tools: {
115
+ delivery: deliveryTools,
116
+ feedback: ["forgejo_get_pull_request", "forgejo_list_pull_request_feedback"],
117
+ ci: [
118
+ "woodpecker_lookup_repository",
119
+ "woodpecker_list_pipelines",
120
+ "woodpecker_get_pipeline",
121
+ "woodpecker_get_step_logs",
122
+ "woodpecker_restart_pipeline",
123
+ ],
124
+ },
125
+ identity: (ctx) => resolvePullRequestGitIdentity(ctx, "forgejo", ctx.params.forgejoProfile),
126
+ reconcileTerminal: reconcilePullRequestSourceIssue<ForgejoRepoChangeParams>(
127
+ "forgejo",
128
+ "id",
129
+ (params) => (isIssueOrigin(params) ? params : undefined),
594
130
  ),
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.`;
131
+ ...pullRequestPublicationCallbacks<ForgejoRepoChangeParams>("forgejo", "Forgejo", (params) =>
132
+ isIssueOrigin(params) ? params : undefined,
133
+ ),
134
+ commitMessage: (kind) =>
135
+ kind === "feedback"
136
+ ? "fix: address Forgejo review feedback"
137
+ : "fix: repair Woodpecker pipeline",
138
+ prompt(kind, current) {
615
139
  return kind === "feedback"
616
140
  ? `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
141
  : `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
142
  },
698
143
  });
699
-
144
+ const publication = publicationConfig.fragment;
700
145
  publication.watcher({
701
146
  id: "use_leitwerk",
702
147
  label: "Forgejo use-leitwerk issues",
703
148
  description: "Launch a remote repository change for Forgejo issues carrying the trigger label",
704
149
  source: forgejoIssueWatcherSource,
705
150
  preparationChecks: launcher.preparationChecks,
706
- async resolveLaunchConfig({ profile, repository, issue, labels }) {
707
- const issueNumber = issue.number;
708
- const title = issue.title.trim();
709
- const body = issue.body?.trim() ?? "";
710
- const issueUrl = issue.html_url;
711
- const binding = launcher.resolveProfiles(profile);
712
- const gitIdentity = await launcher.resolveGitIdentity(profile);
713
- const params: ForgejoRepoChangeParams = {
714
- ...forgejoRepoChangeParams(repository, {
715
- ...binding,
716
- profile,
717
- workBranch: `leitwerk/issue-${issueNumber}`,
718
- prompt: `${title}${body ? `\n\n${body}` : ""}`,
719
- }),
720
- origin: "issue",
721
- issueNumber,
722
- issueUrl,
723
- triggerLabel: labels.trigger,
724
- doneLabel: labels.done,
725
- };
726
- return forgejoRepoChangeLaunchConfig(params, title, gitIdentity);
727
- },
151
+ resolveLaunchConfig: launcher.launcher.resolveIssueLaunchConfig,
728
152
  });
729
153
 
730
154
  const definition = createRepositoryChangeProcess<ForgejoRepoChangeParams>({
@@ -739,7 +163,6 @@ export function createForgejoRepoChangeProcess(
739
163
  fields: [],
740
164
  submitLabel: "Publish",
741
165
  },
742
- finalizationDescription: "Publish feature branch",
743
166
  repositoryCredentials: ({ params }) => [
744
167
  {
745
168
  projectKey: "repo",
@@ -747,11 +170,7 @@ export function createForgejoRepoChangeProcess(
747
170
  credentialRef: params.sshCredentialRef,
748
171
  },
749
172
  ],
750
- publication: {
751
- entryTurnId: ids.deliver,
752
- fragment: publication,
753
- happyPath: [ids.deliver],
754
- },
173
+ publication: publicationConfig,
755
174
  });
756
175
 
757
176
  definition.process.runtime = { ...definition.process.runtime, docker };