@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/dist/index.js ADDED
@@ -0,0 +1,1402 @@
1
+ // src/index.ts
2
+ import { forgejoIntegration } from "@leitwerk-dev/forgejo";
3
+ import { gitSshIntegration } from "@leitwerk-dev/git-ssh";
4
+ import { woodpeckerIntegration } from "@leitwerk-dev/woodpecker";
5
+
6
+ // src/launcher.ts
7
+ import { buildAutoWorkBranchFromSeed } from "@leitwerk-dev/coding/auto-work-branch";
8
+
9
+ // ../../node_modules/valibot/dist/index.mjs
10
+ var store$4;
11
+ // @__NO_SIDE_EFFECTS__
12
+ function getGlobalConfig(config$1) {
13
+ return {
14
+ lang: config$1?.lang ?? store$4?.lang,
15
+ message: config$1?.message,
16
+ abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
17
+ abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
18
+ };
19
+ }
20
+ var store$3;
21
+ // @__NO_SIDE_EFFECTS__
22
+ function getGlobalMessage(lang) {
23
+ return store$3?.get(lang);
24
+ }
25
+ var store$2;
26
+ // @__NO_SIDE_EFFECTS__
27
+ function getSchemaMessage(lang) {
28
+ return store$2?.get(lang);
29
+ }
30
+ var store$1;
31
+ // @__NO_SIDE_EFFECTS__
32
+ function getSpecificMessage(reference, lang) {
33
+ return store$1?.get(reference)?.get(lang);
34
+ }
35
+ // @__NO_SIDE_EFFECTS__
36
+ function _stringify(input) {
37
+ const type = typeof input;
38
+ if (type === "string") return `"${input}"`;
39
+ if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
40
+ if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
41
+ return type;
42
+ }
43
+ function _addIssue(context, label, dataset, config$1, other) {
44
+ const input = other && "input" in other ? other.input : dataset.value;
45
+ const expected = other?.expected ?? context.expects ?? null;
46
+ const received = other?.received ?? /* @__PURE__ */ _stringify(input);
47
+ const issue = {
48
+ kind: context.kind,
49
+ type: context.type,
50
+ input,
51
+ expected,
52
+ received,
53
+ message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
54
+ requirement: context.requirement,
55
+ path: other?.path,
56
+ issues: other?.issues,
57
+ lang: config$1.lang,
58
+ abortEarly: config$1.abortEarly,
59
+ abortPipeEarly: config$1.abortPipeEarly
60
+ };
61
+ const isSchema = context.kind === "schema";
62
+ const message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
63
+ if (message$1 !== void 0) issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
64
+ if (isSchema) dataset.typed = false;
65
+ if (dataset.issues) dataset.issues.push(issue);
66
+ else dataset.issues = [issue];
67
+ }
68
+ // @__NO_SIDE_EFFECTS__
69
+ function _getStandardProps(context) {
70
+ return {
71
+ version: 1,
72
+ vendor: "valibot",
73
+ validate(value$1) {
74
+ return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
75
+ }
76
+ };
77
+ }
78
+ // @__NO_SIDE_EFFECTS__
79
+ function _isValidObjectKey(object$1, key) {
80
+ return Object.hasOwn(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
81
+ }
82
+ // @__NO_SIDE_EFFECTS__
83
+ function check(requirement, message$1) {
84
+ return {
85
+ kind: "validation",
86
+ type: "check",
87
+ reference: check,
88
+ async: false,
89
+ expects: null,
90
+ requirement,
91
+ message: message$1,
92
+ "~run"(dataset, config$1) {
93
+ if (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, "input", dataset, config$1);
94
+ return dataset;
95
+ }
96
+ };
97
+ }
98
+ // @__NO_SIDE_EFFECTS__
99
+ function parseJson(config$1, message$1) {
100
+ return {
101
+ kind: "transformation",
102
+ type: "parse_json",
103
+ reference: parseJson,
104
+ config: config$1,
105
+ message: message$1,
106
+ async: false,
107
+ "~run"(dataset, config$2) {
108
+ try {
109
+ dataset.value = JSON.parse(dataset.value, this.config?.reviver);
110
+ } catch (error) {
111
+ if (error instanceof Error) {
112
+ _addIssue(this, "JSON", dataset, config$2, { received: `"${error.message}"` });
113
+ dataset.typed = false;
114
+ } else throw error;
115
+ }
116
+ return dataset;
117
+ }
118
+ };
119
+ }
120
+ // @__NO_SIDE_EFFECTS__
121
+ function getFallback(schema, dataset, config$1) {
122
+ return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
123
+ }
124
+ // @__NO_SIDE_EFFECTS__
125
+ function getDefault(schema, dataset, config$1) {
126
+ return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
127
+ }
128
+ // @__NO_SIDE_EFFECTS__
129
+ function custom(check$1, message$1) {
130
+ return {
131
+ kind: "schema",
132
+ type: "custom",
133
+ reference: custom,
134
+ expects: "unknown",
135
+ async: false,
136
+ check: check$1,
137
+ message: message$1,
138
+ get "~standard"() {
139
+ return /* @__PURE__ */ _getStandardProps(this);
140
+ },
141
+ "~run"(dataset, config$1) {
142
+ if (this.check(dataset.value)) dataset.typed = true;
143
+ else _addIssue(this, "type", dataset, config$1);
144
+ return dataset;
145
+ }
146
+ };
147
+ }
148
+ // @__NO_SIDE_EFFECTS__
149
+ function object(entries$1, message$1) {
150
+ return {
151
+ kind: "schema",
152
+ type: "object",
153
+ reference: object,
154
+ expects: "Object",
155
+ async: false,
156
+ entries: entries$1,
157
+ message: message$1,
158
+ get "~standard"() {
159
+ return /* @__PURE__ */ _getStandardProps(this);
160
+ },
161
+ "~run"(dataset, config$1) {
162
+ const input = dataset.value;
163
+ if (input && typeof input === "object") {
164
+ dataset.typed = true;
165
+ dataset.value = {};
166
+ for (const key in this.entries) {
167
+ const valueSchema = this.entries[key];
168
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
169
+ const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
170
+ const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
171
+ if (valueDataset.issues) {
172
+ const pathItem = {
173
+ type: "object",
174
+ origin: "value",
175
+ input,
176
+ key,
177
+ value: value$1
178
+ };
179
+ for (const issue of valueDataset.issues) {
180
+ if (issue.path) issue.path.unshift(pathItem);
181
+ else issue.path = [pathItem];
182
+ dataset.issues?.push(issue);
183
+ }
184
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
185
+ if (config$1.abortEarly) {
186
+ dataset.typed = false;
187
+ break;
188
+ }
189
+ }
190
+ if (!valueDataset.typed) dataset.typed = false;
191
+ dataset.value[key] = valueDataset.value;
192
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
193
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
194
+ _addIssue(this, "key", dataset, config$1, {
195
+ input: void 0,
196
+ expected: `"${key}"`,
197
+ path: [{
198
+ type: "object",
199
+ origin: "key",
200
+ input,
201
+ key,
202
+ value: input[key]
203
+ }]
204
+ });
205
+ if (config$1.abortEarly) break;
206
+ }
207
+ }
208
+ } else _addIssue(this, "type", dataset, config$1);
209
+ return dataset;
210
+ }
211
+ };
212
+ }
213
+ // @__NO_SIDE_EFFECTS__
214
+ function optional(wrapped, default_) {
215
+ return {
216
+ kind: "schema",
217
+ type: "optional",
218
+ reference: optional,
219
+ expects: `(${wrapped.expects} | undefined)`,
220
+ async: false,
221
+ wrapped,
222
+ default: default_,
223
+ get "~standard"() {
224
+ return /* @__PURE__ */ _getStandardProps(this);
225
+ },
226
+ "~run"(dataset, config$1) {
227
+ if (dataset.value === void 0) {
228
+ if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
229
+ if (dataset.value === void 0) {
230
+ dataset.typed = true;
231
+ return dataset;
232
+ }
233
+ }
234
+ return this.wrapped["~run"](dataset, config$1);
235
+ }
236
+ };
237
+ }
238
+ // @__NO_SIDE_EFFECTS__
239
+ function record(key, value$1, message$1) {
240
+ return {
241
+ kind: "schema",
242
+ type: "record",
243
+ reference: record,
244
+ expects: "Object",
245
+ async: false,
246
+ key,
247
+ value: value$1,
248
+ message: message$1,
249
+ get "~standard"() {
250
+ return /* @__PURE__ */ _getStandardProps(this);
251
+ },
252
+ "~run"(dataset, config$1) {
253
+ const input = dataset.value;
254
+ if (input && typeof input === "object") {
255
+ dataset.typed = true;
256
+ dataset.value = {};
257
+ for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
258
+ const entryValue = input[entryKey];
259
+ const keyDataset = this.key["~run"]({ value: entryKey }, config$1);
260
+ if (keyDataset.issues) {
261
+ const pathItem = {
262
+ type: "object",
263
+ origin: "key",
264
+ input,
265
+ key: entryKey,
266
+ value: entryValue
267
+ };
268
+ for (const issue of keyDataset.issues) {
269
+ issue.path = [pathItem];
270
+ dataset.issues?.push(issue);
271
+ }
272
+ if (!dataset.issues) dataset.issues = keyDataset.issues;
273
+ if (config$1.abortEarly) {
274
+ dataset.typed = false;
275
+ break;
276
+ }
277
+ }
278
+ const valueDataset = this.value["~run"]({ value: entryValue }, config$1);
279
+ if (valueDataset.issues) {
280
+ const pathItem = {
281
+ type: "object",
282
+ origin: "value",
283
+ input,
284
+ key: entryKey,
285
+ value: entryValue
286
+ };
287
+ for (const issue of valueDataset.issues) {
288
+ if (issue.path) issue.path.unshift(pathItem);
289
+ else issue.path = [pathItem];
290
+ dataset.issues?.push(issue);
291
+ }
292
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
293
+ if (config$1.abortEarly) {
294
+ dataset.typed = false;
295
+ break;
296
+ }
297
+ }
298
+ if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
299
+ if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
300
+ }
301
+ } else _addIssue(this, "type", dataset, config$1);
302
+ return dataset;
303
+ }
304
+ };
305
+ }
306
+ // @__NO_SIDE_EFFECTS__
307
+ function string(message$1) {
308
+ return {
309
+ kind: "schema",
310
+ type: "string",
311
+ reference: string,
312
+ expects: "string",
313
+ async: false,
314
+ message: message$1,
315
+ get "~standard"() {
316
+ return /* @__PURE__ */ _getStandardProps(this);
317
+ },
318
+ "~run"(dataset, config$1) {
319
+ if (typeof dataset.value === "string") dataset.typed = true;
320
+ else _addIssue(this, "type", dataset, config$1);
321
+ return dataset;
322
+ }
323
+ };
324
+ }
325
+ // @__NO_SIDE_EFFECTS__
326
+ function unknown() {
327
+ return {
328
+ kind: "schema",
329
+ type: "unknown",
330
+ reference: unknown,
331
+ expects: "unknown",
332
+ async: false,
333
+ get "~standard"() {
334
+ return /* @__PURE__ */ _getStandardProps(this);
335
+ },
336
+ "~run"(dataset) {
337
+ dataset.typed = true;
338
+ return dataset;
339
+ }
340
+ };
341
+ }
342
+ // @__NO_SIDE_EFFECTS__
343
+ function pipe(...pipe$1) {
344
+ return {
345
+ ...pipe$1[0],
346
+ pipe: pipe$1,
347
+ get "~standard"() {
348
+ return /* @__PURE__ */ _getStandardProps(this);
349
+ },
350
+ "~run"(dataset, config$1) {
351
+ for (const item of pipe$1) if (item.kind !== "metadata") {
352
+ if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
353
+ dataset.typed = false;
354
+ break;
355
+ }
356
+ if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item["~run"](dataset, config$1);
357
+ }
358
+ return dataset;
359
+ }
360
+ };
361
+ }
362
+
363
+ // ../../packages/domain/dist/index.js
364
+ function trimString(value) {
365
+ return typeof value === "string" ? value.trim() : "";
366
+ }
367
+ var SYSTEM_ACTOR = { id: "system", kind: "system", provider: null };
368
+ function serializeActor(actor) {
369
+ return JSON.stringify({
370
+ id: actor.id,
371
+ kind: actor.kind,
372
+ provider: actor.provider,
373
+ ...actor.displayName !== void 0 ? { displayName: actor.displayName } : {}
374
+ });
375
+ }
376
+ var SERIALIZED_SYSTEM_ACTOR = serializeActor(SYSTEM_ACTOR);
377
+ var jsonObjectSchema = custom(
378
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value),
379
+ "Expected object"
380
+ );
381
+ var instanceTurnConfigSchema = pipe(
382
+ jsonObjectSchema,
383
+ object({
384
+ modelProfileId: optional(unknown())
385
+ })
386
+ );
387
+ var strictInstanceTurnConfigsJsonSchema = pipe(
388
+ string(),
389
+ parseJson(),
390
+ jsonObjectSchema,
391
+ record(string(), instanceTurnConfigSchema)
392
+ );
393
+ var copiedUnknownRecordSchema = pipe(
394
+ unknown(),
395
+ check(isUnknownRecord, "Expected object"),
396
+ record(string(), unknown())
397
+ );
398
+ function isUnknownRecord(value) {
399
+ return typeof value === "object" && value !== null && !Array.isArray(value);
400
+ }
401
+ function asUnknownRecord(value) {
402
+ return isUnknownRecord(value) ? value : null;
403
+ }
404
+
405
+ // src/launcher.ts
406
+ import {
407
+ SafeLaunchPreparationError
408
+ } from "@leitwerk-dev/process-sdk";
409
+
410
+ // src/params.ts
411
+ import {
412
+ createRepositoryChangeParamsCodec,
413
+ normalizeRepositoryChangeParamsInput,
414
+ repositoryChangeParamsRecord
415
+ } from "@leitwerk-dev/coding/repository-change-launch";
416
+ function isIssueOrigin(params) {
417
+ return params.origin === "issue";
418
+ }
419
+ var forgejoRepoChangeParamsCodec = createRepositoryChangeParamsCodec({
420
+ displayName: "Forgejo Repo Change",
421
+ normalize(value) {
422
+ const shared = normalizeRepositoryChangeParamsInput(value, "Forgejo Repo Change");
423
+ const record3 = repositoryChangeParamsRecord(value, "Forgejo Repo Change");
424
+ const text = (name) => {
425
+ const value2 = trimString(record3[name]);
426
+ if (!value2) throw new Error(`Forgejo Repo Change requires ${name}`);
427
+ return value2;
428
+ };
429
+ const common = {
430
+ ...shared,
431
+ forgejoProfile: text("forgejoProfile"),
432
+ woodpeckerProfile: text("woodpeckerProfile"),
433
+ sshCredentialRef: text("sshCredentialRef"),
434
+ owner: text("owner"),
435
+ repo: text("repo")
436
+ };
437
+ const origin = trimString(record3.origin);
438
+ if (origin === "ui") {
439
+ return {
440
+ ...common,
441
+ origin: "ui",
442
+ issueNumber: null,
443
+ issueUrl: null,
444
+ triggerLabel: null,
445
+ doneLabel: null
446
+ };
447
+ }
448
+ if (origin && origin !== "issue") {
449
+ throw new Error("Forgejo Repo Change requires a valid origin");
450
+ }
451
+ if (typeof record3.issueNumber !== "number" || !Number.isInteger(record3.issueNumber) || record3.issueNumber <= 0)
452
+ throw new Error("Forgejo Repo Change requires issueNumber");
453
+ return {
454
+ ...common,
455
+ origin: "issue",
456
+ issueNumber: record3.issueNumber,
457
+ issueUrl: text("issueUrl"),
458
+ triggerLabel: text("triggerLabel"),
459
+ doneLabel: text("doneLabel")
460
+ };
461
+ }
462
+ });
463
+
464
+ // src/profile-bindings.ts
465
+ function record2(value, label) {
466
+ if (!value || typeof value !== "object" || Array.isArray(value))
467
+ throw new Error(`${label} must be an object`);
468
+ return value;
469
+ }
470
+ function field(value, fallback, label) {
471
+ if (value === void 0) return fallback;
472
+ if (typeof value !== "string" || !value.trim())
473
+ throw new Error(`${label} must be a non-empty string`);
474
+ return value.trim();
475
+ }
476
+ function parseProfileBindings(raw) {
477
+ const config = raw === void 0 ? {} : record2(raw, "forgejo-repo-change configuration");
478
+ if (config.profile_bindings === void 0) return Object.freeze({});
479
+ const mappings = record2(config.profile_bindings, "profile_bindings");
480
+ const entries = Object.entries(mappings).map(([profile, value]) => {
481
+ if (!profile.trim() || profile.trim() !== profile)
482
+ throw new Error(
483
+ "profile_bindings keys must be non-empty profile names without surrounding whitespace"
484
+ );
485
+ const mapping = record2(value, `profile_bindings.${profile}`);
486
+ for (const key of Object.keys(mapping))
487
+ if (key !== "woodpecker_profile" && key !== "ssh_credential_ref")
488
+ throw new Error(`Unknown profile_bindings.${profile}.${key}`);
489
+ return [
490
+ profile,
491
+ Object.freeze({
492
+ woodpeckerProfile: field(
493
+ mapping.woodpecker_profile,
494
+ profile,
495
+ `profile_bindings.${profile}.woodpecker_profile`
496
+ ),
497
+ sshCredentialRef: field(
498
+ mapping.ssh_credential_ref,
499
+ profile,
500
+ `profile_bindings.${profile}.ssh_credential_ref`
501
+ )
502
+ })
503
+ ];
504
+ });
505
+ return Object.freeze(Object.fromEntries(entries));
506
+ }
507
+ function resolveProfileBinding(bindings, profile) {
508
+ return Object.hasOwn(bindings, profile) ? { ...bindings[profile] } : { woodpeckerProfile: profile, sshCredentialRef: profile };
509
+ }
510
+
511
+ // src/launcher.ts
512
+ var forgejoRepoChangeUiLauncherId = "forgejo_repo_change_process.ui_launcher";
513
+ function forgejoRepoChangeParams(repository, input) {
514
+ return {
515
+ launchKind: "requested_change",
516
+ repoLocator: repository.ssh_url,
517
+ baseBranch: repository.default_branch,
518
+ workBranch: input.workBranch,
519
+ prompt: input.prompt,
520
+ forgejoProfile: input.profile,
521
+ woodpeckerProfile: input.woodpeckerProfile,
522
+ sshCredentialRef: input.sshCredentialRef,
523
+ owner: repository.owner.login,
524
+ repo: repository.name,
525
+ origin: "ui",
526
+ issueNumber: null,
527
+ issueUrl: null,
528
+ triggerLabel: null,
529
+ doneLabel: null
530
+ };
531
+ }
532
+ function forgejoRepoChangeLaunchConfig(params, title, gitIdentity) {
533
+ const { owner, repo, forgejoProfile: profile, woodpeckerProfile } = params;
534
+ const issue = isIssueOrigin(params);
535
+ return {
536
+ processId: "forgejo_repo_change_process",
537
+ params,
538
+ title,
539
+ startTurnId: "generate_plan",
540
+ ...issue ? {
541
+ externalId: `forgejo:${owner}/${repo}#${params.issueNumber}`,
542
+ externalUrl: params.issueUrl
543
+ } : {},
544
+ projects: [
545
+ {
546
+ key: "repo",
547
+ repoLocator: params.repoLocator,
548
+ baseBranch: params.baseBranch,
549
+ workBranch: params.workBranch,
550
+ ...issue ? { externalId: String(params.issueNumber), externalUrl: params.issueUrl } : {},
551
+ metadata: {
552
+ forgejo: { owner, repo, profile, ...issue ? { issueNumber: params.issueNumber } : {} },
553
+ woodpecker: { owner, repo, profile: woodpeckerProfile },
554
+ "leitwerk.gitIdentity": gitIdentity
555
+ }
556
+ }
557
+ ]
558
+ };
559
+ }
560
+ function createForgejoRepoChangeLauncher() {
561
+ let dependencies = null;
562
+ function configureForgejoRepoChangeLauncher2(value) {
563
+ dependencies = value;
564
+ }
565
+ function requireDependencies() {
566
+ if (!dependencies) throw new Error("Forgejo repository launcher is not configured");
567
+ return dependencies;
568
+ }
569
+ function sshPreparationCheck(access, params) {
570
+ return {
571
+ id: `ssh_${access}`,
572
+ label: `Verify SSH ${access} access`,
573
+ async run({ signal, logger }) {
574
+ signal.throwIfAborted();
575
+ const result = await requireDependencies().gitSsh.preflight({
576
+ credentialRef: params.sshCredentialRef,
577
+ repoLocator: params.repoLocator,
578
+ baseBranch: params.baseBranch,
579
+ requireWrite: access === "write"
580
+ });
581
+ signal.throwIfAborted();
582
+ if (!result.ok) {
583
+ logger.warn(`Git SSH ${result.access} preflight failed: ${result.detail}`);
584
+ throw new SafeLaunchPreparationError(
585
+ `SSH ${result.access} access failed: ${result.detail}`,
586
+ `Authorize Git SSH profile '${params.sshCredentialRef}' for '${params.owner}/${params.repo}' with read/write access, then try again.`
587
+ );
588
+ }
589
+ }
590
+ };
591
+ }
592
+ function forgejoRepositoryPreparationChecks2(_input, { params }) {
593
+ return [
594
+ {
595
+ id: "repository_visibility",
596
+ label: "Check repository visibility",
597
+ async run({ signal }) {
598
+ signal.throwIfAborted();
599
+ const repositoryName = `${params.owner}/${params.repo}`;
600
+ const visible = (await repositories(params.forgejoProfile)).some(
601
+ (candidate) => candidate.full_name === repositoryName
602
+ );
603
+ signal.throwIfAborted();
604
+ if (!visible) {
605
+ throw new SafeLaunchPreparationError(
606
+ "Repository is not visible",
607
+ "Grant the selected Forgejo profile access to the repository, then try again."
608
+ );
609
+ }
610
+ }
611
+ },
612
+ sshPreparationCheck("read", params),
613
+ sshPreparationCheck("write", params)
614
+ ];
615
+ }
616
+ function validationError(fieldId, message, code = "required") {
617
+ return { code, fieldId, message };
618
+ }
619
+ function resolveProfiles(profile) {
620
+ const { forgejo, woodpecker, gitSsh, profileBindings = {} } = requireDependencies();
621
+ if (!forgejo.profiles().includes(profile)) throw new Error("Forgejo profile is not available");
622
+ const binding = resolveProfileBinding(profileBindings, profile);
623
+ try {
624
+ woodpecker.client(binding.woodpeckerProfile);
625
+ } catch {
626
+ throw new Error(`Woodpecker profile '${binding.woodpeckerProfile}' is not available`);
627
+ }
628
+ if (!gitSsh.profiles().includes(binding.sshCredentialRef))
629
+ throw new Error(`Git SSH profile '${binding.sshCredentialRef}' is not available`);
630
+ return binding;
631
+ }
632
+ async function resolveForgejoGitIdentity2(profile) {
633
+ if (!profile) throw new Error("A Forgejo profile is required to resolve Git identity");
634
+ return requireDependencies().forgejo.client(profile).resolveGitIdentity(profile);
635
+ }
636
+ async function repositories(profile) {
637
+ if (!profile) return [];
638
+ const { forgejo } = requireDependencies();
639
+ if (!forgejo.profiles().includes(profile)) return [];
640
+ return forgejo.client(profile).listRepositories();
641
+ }
642
+ const forgejoRepoChangeUiLauncher2 = {
643
+ id: forgejoRepoChangeUiLauncherId,
644
+ label: "Forgejo Repo Change",
645
+ description: "Plan, implement, review, and publish a Forgejo change without a source issue",
646
+ visibility: "ui",
647
+ ui: {
648
+ card: {
649
+ title: "Forgejo Repo Change",
650
+ description: "Start a repository change and publish it as a Forgejo pull request."
651
+ },
652
+ launchConfigSchema: {
653
+ id: "forgejo_repo_change_form",
654
+ title: "Forgejo Repo Change",
655
+ fields: [
656
+ {
657
+ id: "forgejoProfile",
658
+ label: "Forgejo profile",
659
+ kind: "select",
660
+ required: true,
661
+ description: "Forgejo profile with server-configured CI and Git SSH access."
662
+ },
663
+ {
664
+ id: "repository",
665
+ label: "Repository",
666
+ kind: "select",
667
+ required: true,
668
+ description: "Repository visible to the selected Forgejo profile."
669
+ },
670
+ {
671
+ id: "prompt",
672
+ label: "Requested change",
673
+ kind: "textarea",
674
+ required: true,
675
+ placeholder: "Describe the change to plan, implement, review, and publish."
676
+ }
677
+ ],
678
+ submitLabel: "Start change"
679
+ },
680
+ resolveDefaults() {
681
+ return {
682
+ forgejoProfile: requireDependencies().forgejo.profiles()[0] ?? "",
683
+ repository: "",
684
+ prompt: ""
685
+ };
686
+ },
687
+ async resolveOptions(input) {
688
+ const { forgejo } = requireDependencies();
689
+ const profile = trimString(input.forgejoProfile);
690
+ return {
691
+ forgejoProfile: forgejo.profiles().map((value) => ({ value, label: value })),
692
+ repository: (await repositories(profile)).map((repository) => ({
693
+ value: repository.full_name,
694
+ label: repository.full_name,
695
+ description: repository.html_url
696
+ }))
697
+ };
698
+ },
699
+ preparationChecks: forgejoRepositoryPreparationChecks2,
700
+ resolveRelaunchInput(previousInput) {
701
+ return {
702
+ forgejoProfile: trimString(previousInput.forgejoProfile),
703
+ repository: trimString(previousInput.repository),
704
+ prompt: trimString(previousInput.prompt)
705
+ };
706
+ },
707
+ async resolveLaunchConfig(input) {
708
+ const profile = trimString(input.forgejoProfile);
709
+ const repositoryName = trimString(input.repository);
710
+ const prompt = trimString(input.prompt);
711
+ const errors = [];
712
+ const invalid = (fieldId, message) => ({
713
+ ok: false,
714
+ errors: [validationError(fieldId, message, "custom_rule")]
715
+ });
716
+ const { forgejo } = requireDependencies();
717
+ if (!profile) errors.push(validationError("forgejoProfile", "Forgejo profile is required"));
718
+ else if (!forgejo.profiles().includes(profile))
719
+ errors.push(
720
+ validationError("forgejoProfile", "Forgejo profile is not available", "custom_rule")
721
+ );
722
+ if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
723
+ if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
724
+ if (errors.length > 0) return { ok: false, errors };
725
+ const repository = (await repositories(profile)).find(
726
+ (candidate) => candidate.full_name === repositoryName
727
+ );
728
+ if (!repository)
729
+ return invalid(
730
+ "repository",
731
+ "Repository is not available to the selected Forgejo profile"
732
+ );
733
+ let binding;
734
+ try {
735
+ binding = resolveProfiles(profile);
736
+ } catch (error) {
737
+ return invalid("forgejoProfile", error.message);
738
+ }
739
+ const gitIdentity = await resolveForgejoGitIdentity2(profile);
740
+ const workBranch = buildAutoWorkBranchFromSeed(
741
+ prompt,
742
+ `${repository.ssh_url}:${repository.default_branch}`
743
+ );
744
+ const params = forgejoRepoChangeParams(repository, {
745
+ ...binding,
746
+ profile,
747
+ prompt,
748
+ workBranch
749
+ });
750
+ return {
751
+ ok: true,
752
+ launchConfig: forgejoRepoChangeLaunchConfig(params, prompt, gitIdentity)
753
+ };
754
+ }
755
+ }
756
+ };
757
+ return {
758
+ configure: configureForgejoRepoChangeLauncher2,
759
+ preparationChecks: forgejoRepositoryPreparationChecks2,
760
+ resolveProfiles,
761
+ resolveGitIdentity: resolveForgejoGitIdentity2,
762
+ launcher: forgejoRepoChangeUiLauncher2
763
+ };
764
+ }
765
+
766
+ // src/process.ts
767
+ import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
768
+ import { commitAndPushWorkBranch } from "@leitwerk-dev/coding/finalization-git";
769
+ import {
770
+ forgejoExternal,
771
+ forgejoIssueWatcherSource
772
+ } from "@leitwerk-dev/forgejo";
773
+ import { flow } from "@leitwerk-dev/process-sdk";
774
+ import {
775
+ conflictKey,
776
+ validateConflict
777
+ } from "@leitwerk-dev/repository-rebase";
778
+ import { publishRebase, startRebase } from "@leitwerk-dev/repository-rebase/git";
779
+ import { rebasePrompt } from "@leitwerk-dev/repository-rebase/prompt";
780
+ import { woodpeckerExternal } from "@leitwerk-dev/woodpecker";
781
+ var processId = "forgejo_repo_change_process";
782
+ var ids = {
783
+ deliver: "deliver_change",
784
+ feedback: "revise_from_pull_request_feedback",
785
+ ciRepair: "repair_woodpecker_pipeline",
786
+ operator: "ci_operator_action"
787
+ };
788
+ var initialDeliveryState = {
789
+ stage: "not_started",
790
+ issueLinked: false,
791
+ adjustment: null,
792
+ terminalPullRequest: null
793
+ };
794
+ var initialRemoteState = {
795
+ headSha: null,
796
+ prNumber: null,
797
+ prUrl: null,
798
+ conversationCursor: 0,
799
+ reviewCursor: 0,
800
+ inlineCursor: 0,
801
+ feedbackIds: [],
802
+ pipeline: null,
803
+ ciRecoveryCycles: 0,
804
+ delivery: initialDeliveryState
805
+ };
806
+ var object2 = (value) => asUnknownRecord(value) ?? {};
807
+ function remote(state) {
808
+ const stored = object2(object2(state.extensionState).forgejoRepoChange);
809
+ return {
810
+ ...initialRemoteState,
811
+ ...stored,
812
+ delivery: {
813
+ ...initialDeliveryState,
814
+ ...object2(stored.delivery)
815
+ }
816
+ };
817
+ }
818
+ function patchRemote(state, patch) {
819
+ const current = remote(state);
820
+ return {
821
+ ...state,
822
+ extensionState: {
823
+ ...state.extensionState,
824
+ forgejoRepoChange: {
825
+ ...current,
826
+ ...patch,
827
+ delivery: { ...current.delivery, ...patch.delivery }
828
+ }
829
+ }
830
+ };
831
+ }
832
+ function requirePr(state) {
833
+ const value = remote(state);
834
+ const { headSha, prNumber, prUrl } = value;
835
+ if (!headSha || !prNumber || !prUrl) {
836
+ throw new Error("Pull request delivery state is incomplete");
837
+ }
838
+ return { ...value, headSha, prNumber, prUrl };
839
+ }
840
+ function feedbackKey(value) {
841
+ return `${value.kind}:${value.id}`;
842
+ }
843
+ function requireIssueOrigin(params) {
844
+ if (!isIssueOrigin(params)) throw new Error("Forgejo source issue metadata is unavailable");
845
+ return params;
846
+ }
847
+ function pinnedGitIdentity(ctx) {
848
+ const project = ctx.projects.find((candidate2) => candidate2.key === "repo");
849
+ const candidate = object2(project?.metadata)?.["leitwerk.gitIdentity"];
850
+ const identity = object2(candidate);
851
+ if (identity.provider !== "forgejo" || identity.profile !== ctx.params.forgejoProfile || typeof identity.login !== "string" || !identity.login.trim() || typeof identity.name !== "string" || !identity.name.trim() || typeof identity.email !== "string" || !identity.email.trim()) {
852
+ return null;
853
+ }
854
+ return identity;
855
+ }
856
+ async function commitWorkBranch(ctx, commitMessage) {
857
+ const repo = ctx.repo.get("repo");
858
+ const gitIdentity = pinnedGitIdentity(ctx) ?? await ctx.callIntegrationTool("forgejo_resolve_git_identity", {
859
+ projectKey: "repo"
860
+ });
861
+ return commitAndPushWorkBranch({
862
+ repoPath: repo.fsPath,
863
+ workBranch: repo.workBranch,
864
+ commitMessage,
865
+ gitIdentity
866
+ });
867
+ }
868
+ function deliveryProgress(value, activeStepId) {
869
+ const delivery = value.delivery;
870
+ const step = (id, label, done) => ({
871
+ id,
872
+ label,
873
+ status: activeStepId === id ? "in_progress" : done ? "completed" : "incomplete"
874
+ });
875
+ const adjustmentHandled = delivery.adjustment === null && delivery.stage === "awaiting" && value.headSha !== null;
876
+ return {
877
+ title: "Delivery progress",
878
+ steps: [
879
+ step("publish_branch", "Publish work branch", value.headSha !== null),
880
+ step("open_pr", "Create or find pull request", value.prNumber !== null),
881
+ step("link_issue", "Link source issue when applicable", delivery.issueLinked),
882
+ step("publish_adjustment", "Publish an adjustment when applicable", adjustmentHandled),
883
+ step(
884
+ "reply_feedback",
885
+ "Acknowledge or reply to feedback when applicable",
886
+ value.feedbackIds.length === 0
887
+ ),
888
+ step("await_evidence", "Await external evidence", delivery.stage === "awaiting"),
889
+ step(
890
+ "reconcile_terminal",
891
+ "Reconcile terminal pull request",
892
+ delivery.terminalPullRequest !== null
893
+ )
894
+ ],
895
+ ...value.prNumber && value.prUrl ? {
896
+ links: [
897
+ {
898
+ id: `forgejo-pr-${value.prNumber}`,
899
+ label: `Forgejo PR #${value.prNumber}`,
900
+ url: value.prUrl,
901
+ kind: "pull_request"
902
+ }
903
+ ]
904
+ } : {}
905
+ };
906
+ }
907
+ var deliveryTools = [
908
+ "forgejo_get_pull_request",
909
+ "forgejo_add_pull_request_comment",
910
+ "forgejo_resolve_git_identity",
911
+ "forgejo_ensure_pull_request",
912
+ "forgejo_add_issue_comment",
913
+ "forgejo_add_pull_request_feedback_reaction",
914
+ "forgejo_reply_to_pull_request_feedback",
915
+ "forgejo_get_issue",
916
+ "forgejo_ensure_label",
917
+ "forgejo_update_issue"
918
+ ];
919
+ function createForgejoRepoChangeProcess(launcher, docker) {
920
+ const publication = flow.fragment(
921
+ "forgejo-publication"
922
+ );
923
+ const failedPipeline = woodpeckerExternal.pipeline(({ params, state }) => {
924
+ const current = requirePr(state);
925
+ return {
926
+ profile: params.woodpeckerProfile,
927
+ owner: params.owner,
928
+ repo: params.repo,
929
+ branch: params.workBranch,
930
+ headSha: current.headSha,
931
+ afterPipelineNumber: current.pipeline?.number ?? 0,
932
+ statuses: ["failure", "error", "killed", "canceled", "cancelled", "declined", "blocked"],
933
+ pollInterval: "30s"
934
+ };
935
+ });
936
+ const delivery = flow.automatic(ids.deliver).description("Deliver").integrationTools(...deliveryTools).run(async (ctx) => {
937
+ const call = (name, args) => ctx.callIntegrationTool(name, { projectKey: "repo", ...args });
938
+ let current = remote(ctx.state);
939
+ const update = (patch) => {
940
+ current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
941
+ };
942
+ const result = (outcome) => ({
943
+ outcome,
944
+ params: { nextState: patchRemote(ctx.state, current) }
945
+ });
946
+ ctx.reportProgress(deliveryProgress(current));
947
+ if (current.delivery.terminalPullRequest) {
948
+ ctx.reportProgress(deliveryProgress(current, "reconcile_terminal"));
949
+ const pr = current.delivery.terminalPullRequest;
950
+ if (isIssueOrigin(ctx.params)) {
951
+ const issue = await call("forgejo_get_issue", {
952
+ issueNumber: ctx.params.issueNumber
953
+ });
954
+ let labels = issue.labels.filter((label) => label.name !== ctx.params.triggerLabel).map((label) => label.id);
955
+ if (pr.merged) {
956
+ const done = await call("forgejo_ensure_label", {
957
+ name: ctx.params.doneLabel
958
+ });
959
+ labels = [.../* @__PURE__ */ new Set([...labels, done.id])];
960
+ }
961
+ await call("forgejo_update_issue", {
962
+ issueNumber: ctx.params.issueNumber,
963
+ patch: { labels, ...pr.merged ? { state: "closed" } : {} },
964
+ writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`
965
+ });
966
+ await call("forgejo_add_issue_comment", {
967
+ issueNumber: ctx.params.issueNumber,
968
+ body: pr.merged ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.` : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
969
+ writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`
970
+ });
971
+ }
972
+ ctx.reportProgress(deliveryProgress(current));
973
+ return result(pr.merged ? "completed" : "aborted");
974
+ }
975
+ if (!current.headSha) {
976
+ ctx.reportProgress(deliveryProgress(current, "publish_branch"));
977
+ const published = await commitWorkBranch(
978
+ ctx,
979
+ ctx.state.finalization.generatedCommitMessage ?? ""
980
+ );
981
+ update({ headSha: published.headSha, pipeline: null });
982
+ }
983
+ if (!current.prNumber || !current.prUrl) {
984
+ ctx.reportProgress(deliveryProgress(current, "open_pr"));
985
+ const project = ctx.repo.get("repo");
986
+ const issueOrigin = isIssueOrigin(ctx.params);
987
+ const pr = await call("forgejo_ensure_pull_request", {
988
+ title: ctx.process.title ?? (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
989
+ body: issueOrigin ? `Implements ${ctx.params.issueUrl}
990
+
991
+ Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
992
+ head: project.workBranch,
993
+ base: project.baseBranch
994
+ });
995
+ if (!pr) throw new Error("Forgejo pull request could not be created or found");
996
+ update({ prNumber: pr.number, prUrl: pr.html_url });
997
+ }
998
+ if (!current.delivery.issueLinked) {
999
+ ctx.reportProgress(deliveryProgress(current, "link_issue"));
1000
+ if (isIssueOrigin(ctx.params)) {
1001
+ await call("forgejo_add_issue_comment", {
1002
+ issueNumber: ctx.params.issueNumber,
1003
+ body: `Leitwerk opened pull request ${current.prUrl}.`,
1004
+ writeKey: `forgejo:${ctx.process.id}:source-pr-link:${current.prNumber}`
1005
+ });
1006
+ }
1007
+ update({ delivery: { issueLinked: true } });
1008
+ }
1009
+ if (current.delivery.adjustment) {
1010
+ const adjustment = current.delivery.adjustment;
1011
+ if (adjustment.publishRequired || adjustment.origin === "rebase") {
1012
+ ctx.reportProgress(deliveryProgress(current, "publish_adjustment"));
1013
+ const published = adjustment.origin === "rebase" ? publishRebase(rebaseInput(ctx)) : await commitWorkBranch(
1014
+ ctx,
1015
+ adjustment.origin === "feedback" ? "fix: address Forgejo review feedback" : "fix: repair Woodpecker pipeline"
1016
+ );
1017
+ if (adjustment.origin === "rebase") {
1018
+ const refreshed = await call("forgejo_get_pull_request", {
1019
+ pullRequestNumber: current.prNumber
1020
+ });
1021
+ if (refreshed.head.sha !== published.headSha)
1022
+ throw new Error("Pull request head has not caught up with rebase publication");
1023
+ }
1024
+ update({ headSha: published.headSha, pipeline: null });
1025
+ }
1026
+ if (adjustment.origin === "rebase")
1027
+ await call("forgejo_add_pull_request_comment", {
1028
+ pullRequestNumber: current.prNumber,
1029
+ body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
1030
+ writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`
1031
+ });
1032
+ if (adjustment.origin === "feedback") {
1033
+ ctx.reportProgress(deliveryProgress(current, "reply_feedback"));
1034
+ for (const feedback of current.feedbackIds) {
1035
+ await call("forgejo_reply_to_pull_request_feedback", {
1036
+ pullRequestNumber: current.prNumber,
1037
+ feedbackKind: feedback.kind,
1038
+ feedbackId: feedback.id,
1039
+ body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
1040
+ writeKey: `forgejo:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`
1041
+ });
1042
+ }
1043
+ }
1044
+ update({
1045
+ ...adjustment.origin === "feedback" ? { feedbackIds: [] } : {},
1046
+ delivery: { adjustment: null }
1047
+ });
1048
+ }
1049
+ if (current.feedbackIds.length > 0) {
1050
+ ctx.reportProgress(deliveryProgress(current, "reply_feedback"));
1051
+ for (const feedback of current.feedbackIds) {
1052
+ if (feedback.kind === "review") continue;
1053
+ await call("forgejo_add_pull_request_feedback_reaction", {
1054
+ pullRequestNumber: current.prNumber,
1055
+ feedbackKind: feedback.kind,
1056
+ feedbackId: feedback.id,
1057
+ writeKey: `forgejo:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`
1058
+ });
1059
+ }
1060
+ return result("feedback_ready");
1061
+ }
1062
+ update({ delivery: { stage: "awaiting" } });
1063
+ ctx.reportProgress(deliveryProgress(current, "await_evidence"));
1064
+ return result("awaiting");
1065
+ }).outcome(
1066
+ "awaiting",
1067
+ (outcome) => outcome.description("Delivery is waiting for external evidence").object("nextState").wait().state(({ event }) => event.params.nextState)
1068
+ ).outcome(
1069
+ "feedback_ready",
1070
+ (outcome) => outcome.description("Pull request feedback is acknowledged and ready for revision").object("nextState").to(ids.feedback).state(({ event }) => event.params.nextState)
1071
+ ).outcome(
1072
+ "completed",
1073
+ (outcome) => outcome.description("Merged pull request was reconciled").object("nextState").complete().state(({ event }) => event.params.nextState)
1074
+ ).outcome(
1075
+ "aborted",
1076
+ (outcome) => outcome.description("Closed pull request was reconciled").object("nextState").lifecycleStatus("aborted").state(({ event }) => event.params.nextState)
1077
+ ).externalAction(
1078
+ "forgejo_merge_conflict",
1079
+ forgejoExternal.pullRequestConflict(({ params, state }) => ({
1080
+ profile: params.forgejoProfile,
1081
+ owner: params.owner,
1082
+ repo: params.repo,
1083
+ prNumber: requirePr(state).prNumber,
1084
+ headSha: requirePr(state).headSha,
1085
+ lastConflictKey: remote(state).lastConflictKey,
1086
+ pollInterval: "30s"
1087
+ })),
1088
+ (external) => external.label("Rebase conflicting pull request").to(ids.feedback).effect(({ params, state, event }) => {
1089
+ const current = requirePr(state);
1090
+ const conflict = validateConflict(
1091
+ object2(event).conflict,
1092
+ {
1093
+ owner: params.owner,
1094
+ repo: params.repo,
1095
+ prNumber: current.prNumber,
1096
+ headSha: current.headSha,
1097
+ headBranch: params.workBranch,
1098
+ baseBranch: params.baseBranch
1099
+ },
1100
+ current.lastConflictKey
1101
+ );
1102
+ return {
1103
+ state: patchRemote(state, {
1104
+ lastConflictKey: conflictKey(conflict),
1105
+ conflict,
1106
+ repairReason: "rebase"
1107
+ })
1108
+ };
1109
+ })
1110
+ ).externalAction(
1111
+ "forgejo_feedback",
1112
+ forgejoExternal.pullRequestFeedback(({ params, state }) => {
1113
+ const current = requirePr(state);
1114
+ return {
1115
+ profile: params.forgejoProfile,
1116
+ owner: params.owner,
1117
+ repo: params.repo,
1118
+ prNumber: current.prNumber,
1119
+ conversationCursor: current.conversationCursor,
1120
+ reviewCursor: current.reviewCursor,
1121
+ inlineCursor: current.inlineCursor,
1122
+ quietPeriodMs: 12e4,
1123
+ pollInterval: "30s"
1124
+ };
1125
+ }),
1126
+ (external) => external.label("Forgejo pull request feedback").to(ids.deliver).effect(({ state, event }) => {
1127
+ const value = object2(event);
1128
+ const cursors = object2(value.cursors);
1129
+ return {
1130
+ state: patchRemote(state, {
1131
+ repairReason: "feedback",
1132
+ conversationCursor: Number(
1133
+ cursors.conversationCursor ?? remote(state).conversationCursor
1134
+ ),
1135
+ reviewCursor: Number(cursors.reviewCursor ?? remote(state).reviewCursor),
1136
+ inlineCursor: Number(cursors.inlineCursor ?? remote(state).inlineCursor),
1137
+ feedbackIds: Array.isArray(value.feedbackIds) ? value.feedbackIds : []
1138
+ })
1139
+ };
1140
+ })
1141
+ ).externalAction(
1142
+ "woodpecker_failure_repair",
1143
+ failedPipeline,
1144
+ (external) => external.label("Repair failed Woodpecker pipeline").when(({ state }) => remote(state).ciRecoveryCycles < 3).to(ids.ciRepair).effect(({ state, event }) => ({
1145
+ state: patchRemote(state, {
1146
+ repairReason: "ci",
1147
+ pipeline: object2(event).pipeline,
1148
+ ciRecoveryCycles: remote(state).ciRecoveryCycles + 1
1149
+ })
1150
+ }))
1151
+ ).externalAction(
1152
+ "woodpecker_failure_operator",
1153
+ failedPipeline,
1154
+ (external) => external.label("Escalate failed Woodpecker pipeline").when(({ state }) => remote(state).ciRecoveryCycles >= 3).to(ids.operator).effect(({ state, event }) => ({
1155
+ state: patchRemote(state, {
1156
+ repairReason: "ci",
1157
+ pipeline: object2(event).pipeline
1158
+ })
1159
+ }))
1160
+ );
1161
+ for (const [terminalOutcome, label] of [
1162
+ ["merged", "Forgejo pull request merged"],
1163
+ ["closed", "Forgejo pull request closed without merge"]
1164
+ ]) {
1165
+ delivery.externalAction(
1166
+ `forgejo_pr_${terminalOutcome}`,
1167
+ forgejoExternal.pullRequestTerminal(({ params, state }) => ({
1168
+ profile: params.forgejoProfile,
1169
+ owner: params.owner,
1170
+ repo: params.repo,
1171
+ prNumber: requirePr(state).prNumber,
1172
+ terminalOutcome,
1173
+ pollInterval: "30s"
1174
+ })),
1175
+ (external) => external.label(label).to(ids.deliver).effect(({ state, event }) => ({
1176
+ state: patchRemote(state, {
1177
+ delivery: { terminalPullRequest: object2(event).pullRequest }
1178
+ })
1179
+ }))
1180
+ );
1181
+ }
1182
+ publication.turn(
1183
+ delivery.externalAction(
1184
+ "source_cancelled",
1185
+ forgejoExternal.issueCancelled(({ params }) => {
1186
+ const issue = requireIssueOrigin(params);
1187
+ return {
1188
+ profile: issue.forgejoProfile,
1189
+ owner: issue.owner,
1190
+ repo: issue.repo,
1191
+ issueNumber: issue.issueNumber,
1192
+ triggerLabel: issue.triggerLabel,
1193
+ pollInterval: "30s"
1194
+ };
1195
+ }),
1196
+ (external) => external.label("Source issue cancelled").when(({ params }) => isIssueOrigin(params)).lifecycleStatus("aborted")
1197
+ )
1198
+ );
1199
+ function rebaseInput(ctx) {
1200
+ const project = ctx.repo.get("repo");
1201
+ const conflict = remote(ctx.state).conflict;
1202
+ if (!conflict) throw new Error("Missing conflict evidence");
1203
+ return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
1204
+ }
1205
+ function repairReason(state, kind) {
1206
+ return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
1207
+ }
1208
+ function revisionPrompt(kind) {
1209
+ return (ctx) => {
1210
+ const current = remote(ctx.state);
1211
+ if (repairReason(ctx.state, kind) === "rebase")
1212
+ return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
1213
+ return kind === "feedback" ? `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.` : `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.`;
1214
+ };
1215
+ }
1216
+ function revisionTurn(id, kind) {
1217
+ const turn = flow.llm(id).description(kind === "feedback" ? "Address Feedback" : "Fix CI").tools("read", "bash", "edit", "write").resolveIntegrationTools(
1218
+ (_params, state) => repairReason(state, kind) === "rebase" ? [] : kind === "feedback" ? ["forgejo_get_pull_request", "forgejo_list_pull_request_feedback"] : [
1219
+ "woodpecker_lookup_repository",
1220
+ "woodpecker_list_pipelines",
1221
+ "woodpecker_get_pipeline",
1222
+ "woodpecker_get_step_logs",
1223
+ "woodpecker_restart_pipeline"
1224
+ ]
1225
+ ).prepare(
1226
+ (ctx) => repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {}
1227
+ ).freshPrimary().prompt(revisionPrompt(kind));
1228
+ for (const [name, description, publishRequired] of [
1229
+ ["changes_ready", "Repository changes are ready to publish", true],
1230
+ ["no_changes", "No repository change is required", false]
1231
+ ]) {
1232
+ turn.outcomeTool(
1233
+ name,
1234
+ (tool) => tool.resultSummary().description(description).to(ids.deliver).state(
1235
+ ({ ctx }) => patchRemote(ctx.state, {
1236
+ delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } }
1237
+ })
1238
+ )
1239
+ );
1240
+ }
1241
+ return turn.outcomeTool(
1242
+ "cannot_repair",
1243
+ (tool) => tool.description("The adjustment requires operator action").to(ids.operator)
1244
+ );
1245
+ }
1246
+ publication.turn(revisionTurn(ids.feedback, "feedback"));
1247
+ publication.turn(revisionTurn(ids.ciRepair, "ci"));
1248
+ publication.turn({
1249
+ id: ids.operator,
1250
+ definition: {
1251
+ kind: "human",
1252
+ description: "Repository repair needs operator action",
1253
+ operatorAttention: "required",
1254
+ actions: {
1255
+ retry_repair: {
1256
+ label: "Retry repair",
1257
+ acceptanceState: "accepted",
1258
+ branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
1259
+ choose: ({ ctx }) => remote(ctx.state).repairReason === "rebase" || remote(ctx.state).repairReason === "feedback" ? "feedback" : "ci"
1260
+ },
1261
+ resume_waiting: {
1262
+ label: "Resume waiting",
1263
+ acceptanceState: "accepted",
1264
+ to: ids.deliver,
1265
+ effect: ({ ctx }) => ({
1266
+ state: patchRemote(ctx.state, {
1267
+ feedbackIds: [],
1268
+ delivery: { adjustment: null }
1269
+ })
1270
+ })
1271
+ },
1272
+ abort: { label: "Abort process", acceptanceState: "neutral", lifecycleStatus: "aborted" }
1273
+ }
1274
+ }
1275
+ });
1276
+ publication.watcher({
1277
+ id: "use_leitwerk",
1278
+ label: "Forgejo use-leitwerk issues",
1279
+ description: "Launch a remote repository change for Forgejo issues carrying the trigger label",
1280
+ source: forgejoIssueWatcherSource,
1281
+ preparationChecks: launcher.preparationChecks,
1282
+ async resolveLaunchConfig({ profile, repository, issue, labels }) {
1283
+ const issueNumber = issue.number;
1284
+ const title = issue.title.trim();
1285
+ const body = issue.body?.trim() ?? "";
1286
+ const issueUrl = issue.html_url;
1287
+ const binding = launcher.resolveProfiles(profile);
1288
+ const gitIdentity = await launcher.resolveGitIdentity(profile);
1289
+ const params = {
1290
+ ...forgejoRepoChangeParams(repository, {
1291
+ ...binding,
1292
+ profile,
1293
+ workBranch: `leitwerk/issue-${issueNumber}`,
1294
+ prompt: `${title}${body ? `
1295
+
1296
+ ${body}` : ""}`
1297
+ }),
1298
+ origin: "issue",
1299
+ issueNumber,
1300
+ issueUrl,
1301
+ triggerLabel: labels.trigger,
1302
+ doneLabel: labels.done
1303
+ };
1304
+ return forgejoRepoChangeLaunchConfig(params, title, gitIdentity);
1305
+ }
1306
+ });
1307
+ const definition = createRepositoryChangeProcess({
1308
+ processId,
1309
+ displayName: "Forgejo Repo Change",
1310
+ paramsCodec: forgejoRepoChangeParamsCodec,
1311
+ launcher: launcher.launcher,
1312
+ finalizeLabel: "Publish pull request",
1313
+ finalizeForm: {
1314
+ id: "forgejo_publish",
1315
+ title: "Publish pull request",
1316
+ fields: [],
1317
+ submitLabel: "Publish"
1318
+ },
1319
+ finalizationDescription: "Publish feature branch",
1320
+ repositoryCredentials: ({ params }) => [
1321
+ {
1322
+ projectKey: "repo",
1323
+ kind: "git_ssh",
1324
+ credentialRef: params.sshCredentialRef
1325
+ }
1326
+ ],
1327
+ publication: {
1328
+ entryTurnId: ids.deliver,
1329
+ fragment: publication,
1330
+ happyPath: [ids.deliver]
1331
+ }
1332
+ });
1333
+ definition.process.runtime = { ...definition.process.runtime, docker };
1334
+ return definition.process;
1335
+ }
1336
+
1337
+ // src/index.ts
1338
+ var manifest = {
1339
+ id: "forgejo-repo-change",
1340
+ version: "0.1.9",
1341
+ requires: ["forgejo", "woodpecker", "coding", "git-ssh"]
1342
+ };
1343
+ function createForgejoRepoChange(options) {
1344
+ if (typeof options.docker !== "boolean") throw new Error("docker must be a boolean");
1345
+ const launcher = createForgejoRepoChangeLauncher();
1346
+ const process = createForgejoRepoChangeProcess(launcher, options.docker);
1347
+ const extension = {
1348
+ manifest,
1349
+ setupCatalog(api) {
1350
+ api.registerProcess(process);
1351
+ },
1352
+ setupServer(api, config) {
1353
+ const forgejo = api.require(forgejoIntegration);
1354
+ const gitSsh = api.require(gitSshIntegration);
1355
+ const woodpecker = api.require(woodpeckerIntegration);
1356
+ if (Array.isArray(forgejo) || Array.isArray(gitSsh) || Array.isArray(woodpecker))
1357
+ throw new Error("Repository delivery integrations must be singular");
1358
+ launcher.configure({
1359
+ forgejo,
1360
+ gitSsh,
1361
+ woodpecker,
1362
+ profileBindings: parseProfileBindings(config)
1363
+ });
1364
+ api.onStop(() => launcher.configure(null));
1365
+ }
1366
+ };
1367
+ return { extension, process, launcher };
1368
+ }
1369
+ var {
1370
+ extension: defaultExtension,
1371
+ process: forgejoRepoChangeProcess,
1372
+ launcher: defaultForgejoRepoChangeLauncher
1373
+ } = createForgejoRepoChange({ docker: true });
1374
+ var {
1375
+ configure: configureForgejoRepoChangeLauncher,
1376
+ preparationChecks: forgejoRepositoryPreparationChecks,
1377
+ resolveGitIdentity: resolveForgejoGitIdentity,
1378
+ launcher: forgejoRepoChangeUiLauncher
1379
+ } = defaultForgejoRepoChangeLauncher;
1380
+ var index_default = defaultExtension;
1381
+ export {
1382
+ configureForgejoRepoChangeLauncher,
1383
+ createForgejoRepoChange,
1384
+ createForgejoRepoChangeLauncher,
1385
+ createForgejoRepoChangeProcess,
1386
+ index_default as default,
1387
+ defaultExtension,
1388
+ defaultForgejoRepoChangeLauncher,
1389
+ forgejoRepoChangeLaunchConfig,
1390
+ forgejoRepoChangeParams,
1391
+ forgejoRepoChangeParamsCodec,
1392
+ forgejoRepoChangeProcess,
1393
+ forgejoRepoChangeUiLauncher,
1394
+ forgejoRepoChangeUiLauncherId,
1395
+ forgejoRepositoryPreparationChecks,
1396
+ isIssueOrigin,
1397
+ manifest,
1398
+ parseProfileBindings,
1399
+ resolveForgejoGitIdentity,
1400
+ resolveProfileBinding
1401
+ };
1402
+ //# sourceMappingURL=index.js.map