@leitwerk-dev/forgejo-repo-change 0.0.0-bootstrap.0 → 0.2.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 ADDED
@@ -0,0 +1,759 @@
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
+ import {
21
+ type createForgejoRepoChangeLauncher,
22
+ forgejoRepoChangeLaunchConfig,
23
+ forgejoRepoChangeParams,
24
+ } from "./launcher.js";
25
+ import {
26
+ type ForgejoIssueOriginParams,
27
+ type ForgejoRepoChangeParams,
28
+ forgejoRepoChangeParamsCodec,
29
+ isIssueOrigin,
30
+ } from "./params.js";
31
+
32
+ const processId = "forgejo_repo_change_process";
33
+ const ids = {
34
+ deliver: "deliver_change",
35
+ feedback: "revise_from_pull_request_feedback",
36
+ ciRepair: "repair_woodpecker_pipeline",
37
+ 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
+ };
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
+ }
225
+
226
+ const deliveryTools = [
227
+ "forgejo_get_pull_request",
228
+ "forgejo_add_pull_request_comment",
229
+ "forgejo_resolve_git_identity",
230
+ "forgejo_ensure_pull_request",
231
+ "forgejo_add_issue_comment",
232
+ "forgejo_add_pull_request_feedback_reaction",
233
+ "forgejo_reply_to_pull_request_feedback",
234
+ "forgejo_get_issue",
235
+ "forgejo_ensure_label",
236
+ "forgejo_update_issue",
237
+ ] as const;
238
+
239
+ export function createForgejoRepoChangeProcess(
240
+ launcher: ReturnType<typeof createForgejoRepoChangeLauncher>,
241
+ docker: boolean,
242
+ ) {
243
+ const publication = flow.fragment<ForgejoRepoChangeParams, RepositoryChangeState>(
244
+ "forgejo-publication",
245
+ );
246
+
247
+ const failedPipeline = woodpeckerExternal.pipeline<
248
+ ForgejoRepoChangeParams,
249
+ RepositoryChangeState
250
+ >(({ params, state }) => {
251
+ const current = requirePr(state);
252
+ return {
253
+ profile: params.woodpeckerProfile,
254
+ owner: params.owner,
255
+ repo: params.repo,
256
+ branch: params.workBranch,
257
+ headSha: current.headSha,
258
+ afterPipelineNumber: current.pipeline?.number ?? 0,
259
+ statuses: ["failure", "error", "killed", "canceled", "cancelled", "declined", "blocked"],
260
+ pollInterval: "30s",
261
+ };
262
+ });
263
+
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 }) => ({
451
+ profile: params.forgejoProfile,
452
+ owner: params.owner,
453
+ repo: params.repo,
454
+ prNumber: requirePr(state).prNumber,
455
+ headSha: requirePr(state).headSha,
456
+ lastConflictKey: remote(state).lastConflictKey,
457
+ pollInterval: "30s",
458
+ })),
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
+ };
501
+ }),
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 }) => ({
556
+ profile: params.forgejoProfile,
557
+ owner: params.owner,
558
+ repo: params.repo,
559
+ prNumber: requirePr(state).prNumber,
560
+ terminalOutcome,
561
+ pollInterval: "30s",
562
+ })),
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 }) => {
578
+ const issue = requireIssueOrigin(params);
579
+ return {
580
+ profile: issue.forgejoProfile,
581
+ owner: issue.owner,
582
+ repo: issue.repo,
583
+ issueNumber: issue.issueNumber,
584
+ triggerLabel: issue.triggerLabel,
585
+ pollInterval: "30s",
586
+ };
587
+ }),
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.`;
614
+ return kind === "feedback"
615
+ ? `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
+ : `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
+ },
697
+ });
698
+
699
+ publication.watcher({
700
+ id: "use_leitwerk",
701
+ label: "Forgejo use-leitwerk issues",
702
+ description: "Launch a remote repository change for Forgejo issues carrying the trigger label",
703
+ source: forgejoIssueWatcherSource,
704
+ preparationChecks: launcher.preparationChecks,
705
+ async resolveLaunchConfig({ profile, repository, issue, labels }) {
706
+ const issueNumber = issue.number;
707
+ const title = issue.title.trim();
708
+ const body = issue.body?.trim() ?? "";
709
+ const issueUrl = issue.html_url;
710
+ const binding = launcher.resolveProfiles(profile);
711
+ const gitIdentity = await launcher.resolveGitIdentity(profile);
712
+ const params: ForgejoRepoChangeParams = {
713
+ ...forgejoRepoChangeParams(repository, {
714
+ ...binding,
715
+ profile,
716
+ workBranch: `leitwerk/issue-${issueNumber}`,
717
+ prompt: `${title}${body ? `\n\n${body}` : ""}`,
718
+ }),
719
+ origin: "issue",
720
+ issueNumber,
721
+ issueUrl,
722
+ triggerLabel: labels.trigger,
723
+ doneLabel: labels.done,
724
+ };
725
+ return forgejoRepoChangeLaunchConfig(params, title, gitIdentity);
726
+ },
727
+ });
728
+
729
+ const definition = createRepositoryChangeProcess<ForgejoRepoChangeParams>({
730
+ processId,
731
+ displayName: "Forgejo Repo Change",
732
+ paramsCodec: forgejoRepoChangeParamsCodec,
733
+ launcher: launcher.launcher,
734
+ finalizeLabel: "Publish pull request",
735
+ finalizeForm: {
736
+ id: "forgejo_publish",
737
+ title: "Publish pull request",
738
+ fields: [],
739
+ submitLabel: "Publish",
740
+ },
741
+ finalizationDescription: "Publish feature branch",
742
+ repositoryCredentials: ({ params }) => [
743
+ {
744
+ projectKey: "repo",
745
+ kind: "git_ssh",
746
+ credentialRef: params.sshCredentialRef,
747
+ },
748
+ ],
749
+ publication: {
750
+ entryTurnId: ids.deliver,
751
+ fragment: publication,
752
+ happyPath: [ids.deliver],
753
+ },
754
+ });
755
+
756
+ definition.process.runtime = { ...definition.process.runtime, docker };
757
+
758
+ return definition.process;
759
+ }