@leitwerk-dev/github-repo-change 0.3.0 → 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/dist/index.js CHANGED
@@ -2,496 +2,38 @@
2
2
  import { gitSshIntegration } from "@leitwerk-dev/git-ssh";
3
3
  import { githubIntegration } from "@leitwerk-dev/github";
4
4
 
5
- // src/launcher.ts
6
- import { buildAutoWorkBranchFromSeed } from "@leitwerk-dev/coding/auto-work-branch";
7
-
8
- // ../../node_modules/valibot/dist/index.mjs
9
- var store$4;
10
- // @__NO_SIDE_EFFECTS__
11
- function getGlobalConfig(config$1) {
12
- return {
13
- lang: config$1?.lang ?? store$4?.lang,
14
- message: config$1?.message,
15
- abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
16
- abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
17
- };
18
- }
19
- var store$3;
20
- // @__NO_SIDE_EFFECTS__
21
- function getGlobalMessage(lang) {
22
- return store$3?.get(lang);
23
- }
24
- var store$2;
25
- // @__NO_SIDE_EFFECTS__
26
- function getSchemaMessage(lang) {
27
- return store$2?.get(lang);
28
- }
29
- var store$1;
30
- // @__NO_SIDE_EFFECTS__
31
- function getSpecificMessage(reference, lang) {
32
- return store$1?.get(reference)?.get(lang);
33
- }
34
- // @__NO_SIDE_EFFECTS__
35
- function _stringify(input) {
36
- const type = typeof input;
37
- if (type === "string") return `"${input}"`;
38
- if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
39
- if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
40
- return type;
41
- }
42
- function _addIssue(context, label, dataset, config$1, other) {
43
- const input = other && "input" in other ? other.input : dataset.value;
44
- const expected = other?.expected ?? context.expects ?? null;
45
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
46
- const issue = {
47
- kind: context.kind,
48
- type: context.type,
49
- input,
50
- expected,
51
- received,
52
- message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
53
- requirement: context.requirement,
54
- path: other?.path,
55
- issues: other?.issues,
56
- lang: config$1.lang,
57
- abortEarly: config$1.abortEarly,
58
- abortPipeEarly: config$1.abortPipeEarly
59
- };
60
- const isSchema = context.kind === "schema";
61
- 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);
62
- if (message$1 !== void 0) issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
63
- if (isSchema) dataset.typed = false;
64
- if (dataset.issues) dataset.issues.push(issue);
65
- else dataset.issues = [issue];
66
- }
67
- // @__NO_SIDE_EFFECTS__
68
- function _getStandardProps(context) {
69
- return {
70
- version: 1,
71
- vendor: "valibot",
72
- validate(value$1) {
73
- return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
74
- }
75
- };
76
- }
77
- // @__NO_SIDE_EFFECTS__
78
- function _isValidObjectKey(object$1, key) {
79
- return Object.hasOwn(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
80
- }
81
- // @__NO_SIDE_EFFECTS__
82
- function check(requirement, message$1) {
83
- return {
84
- kind: "validation",
85
- type: "check",
86
- reference: check,
87
- async: false,
88
- expects: null,
89
- requirement,
90
- message: message$1,
91
- "~run"(dataset, config$1) {
92
- if (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, "input", dataset, config$1);
93
- return dataset;
94
- }
95
- };
96
- }
97
- // @__NO_SIDE_EFFECTS__
98
- function parseJson(config$1, message$1) {
99
- return {
100
- kind: "transformation",
101
- type: "parse_json",
102
- reference: parseJson,
103
- config: config$1,
104
- message: message$1,
105
- async: false,
106
- "~run"(dataset, config$2) {
107
- try {
108
- dataset.value = JSON.parse(dataset.value, this.config?.reviver);
109
- } catch (error) {
110
- if (error instanceof Error) {
111
- _addIssue(this, "JSON", dataset, config$2, { received: `"${error.message}"` });
112
- dataset.typed = false;
113
- } else throw error;
114
- }
115
- return dataset;
116
- }
117
- };
118
- }
119
- // @__NO_SIDE_EFFECTS__
120
- function getFallback(schema, dataset, config$1) {
121
- return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
122
- }
123
- // @__NO_SIDE_EFFECTS__
124
- function getDefault(schema, dataset, config$1) {
125
- return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
126
- }
127
- // @__NO_SIDE_EFFECTS__
128
- function custom(check$1, message$1) {
129
- return {
130
- kind: "schema",
131
- type: "custom",
132
- reference: custom,
133
- expects: "unknown",
134
- async: false,
135
- check: check$1,
136
- message: message$1,
137
- get "~standard"() {
138
- return /* @__PURE__ */ _getStandardProps(this);
139
- },
140
- "~run"(dataset, config$1) {
141
- if (this.check(dataset.value)) dataset.typed = true;
142
- else _addIssue(this, "type", dataset, config$1);
143
- return dataset;
144
- }
145
- };
146
- }
147
- // @__NO_SIDE_EFFECTS__
148
- function object(entries$1, message$1) {
149
- return {
150
- kind: "schema",
151
- type: "object",
152
- reference: object,
153
- expects: "Object",
154
- async: false,
155
- entries: entries$1,
156
- message: message$1,
157
- get "~standard"() {
158
- return /* @__PURE__ */ _getStandardProps(this);
159
- },
160
- "~run"(dataset, config$1) {
161
- const input = dataset.value;
162
- if (input && typeof input === "object") {
163
- dataset.typed = true;
164
- dataset.value = {};
165
- for (const key in this.entries) {
166
- const valueSchema = this.entries[key];
167
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
168
- const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
169
- const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
170
- if (valueDataset.issues) {
171
- const pathItem = {
172
- type: "object",
173
- origin: "value",
174
- input,
175
- key,
176
- value: value$1
177
- };
178
- for (const issue of valueDataset.issues) {
179
- if (issue.path) issue.path.unshift(pathItem);
180
- else issue.path = [pathItem];
181
- dataset.issues?.push(issue);
182
- }
183
- if (!dataset.issues) dataset.issues = valueDataset.issues;
184
- if (config$1.abortEarly) {
185
- dataset.typed = false;
186
- break;
187
- }
188
- }
189
- if (!valueDataset.typed) dataset.typed = false;
190
- dataset.value[key] = valueDataset.value;
191
- } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
192
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
193
- _addIssue(this, "key", dataset, config$1, {
194
- input: void 0,
195
- expected: `"${key}"`,
196
- path: [{
197
- type: "object",
198
- origin: "key",
199
- input,
200
- key,
201
- value: input[key]
202
- }]
203
- });
204
- if (config$1.abortEarly) break;
205
- }
206
- }
207
- } else _addIssue(this, "type", dataset, config$1);
208
- return dataset;
209
- }
210
- };
211
- }
212
- // @__NO_SIDE_EFFECTS__
213
- function optional(wrapped, default_) {
214
- return {
215
- kind: "schema",
216
- type: "optional",
217
- reference: optional,
218
- expects: `(${wrapped.expects} | undefined)`,
219
- async: false,
220
- wrapped,
221
- default: default_,
222
- get "~standard"() {
223
- return /* @__PURE__ */ _getStandardProps(this);
224
- },
225
- "~run"(dataset, config$1) {
226
- if (dataset.value === void 0) {
227
- if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
228
- if (dataset.value === void 0) {
229
- dataset.typed = true;
230
- return dataset;
231
- }
232
- }
233
- return this.wrapped["~run"](dataset, config$1);
234
- }
235
- };
236
- }
237
- // @__NO_SIDE_EFFECTS__
238
- function record(key, value$1, message$1) {
239
- return {
240
- kind: "schema",
241
- type: "record",
242
- reference: record,
243
- expects: "Object",
244
- async: false,
245
- key,
246
- value: value$1,
247
- message: message$1,
248
- get "~standard"() {
249
- return /* @__PURE__ */ _getStandardProps(this);
250
- },
251
- "~run"(dataset, config$1) {
252
- const input = dataset.value;
253
- if (input && typeof input === "object") {
254
- dataset.typed = true;
255
- dataset.value = {};
256
- for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
257
- const entryValue = input[entryKey];
258
- const keyDataset = this.key["~run"]({ value: entryKey }, config$1);
259
- if (keyDataset.issues) {
260
- const pathItem = {
261
- type: "object",
262
- origin: "key",
263
- input,
264
- key: entryKey,
265
- value: entryValue
266
- };
267
- for (const issue of keyDataset.issues) {
268
- issue.path = [pathItem];
269
- dataset.issues?.push(issue);
270
- }
271
- if (!dataset.issues) dataset.issues = keyDataset.issues;
272
- if (config$1.abortEarly) {
273
- dataset.typed = false;
274
- break;
275
- }
276
- }
277
- const valueDataset = this.value["~run"]({ value: entryValue }, config$1);
278
- if (valueDataset.issues) {
279
- const pathItem = {
280
- type: "object",
281
- origin: "value",
282
- input,
283
- key: entryKey,
284
- value: entryValue
285
- };
286
- for (const issue of valueDataset.issues) {
287
- if (issue.path) issue.path.unshift(pathItem);
288
- else issue.path = [pathItem];
289
- dataset.issues?.push(issue);
290
- }
291
- if (!dataset.issues) dataset.issues = valueDataset.issues;
292
- if (config$1.abortEarly) {
293
- dataset.typed = false;
294
- break;
295
- }
296
- }
297
- if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
298
- if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
299
- }
300
- } else _addIssue(this, "type", dataset, config$1);
301
- return dataset;
302
- }
303
- };
304
- }
305
- // @__NO_SIDE_EFFECTS__
306
- function string(message$1) {
307
- return {
308
- kind: "schema",
309
- type: "string",
310
- reference: string,
311
- expects: "string",
312
- async: false,
313
- message: message$1,
314
- get "~standard"() {
315
- return /* @__PURE__ */ _getStandardProps(this);
316
- },
317
- "~run"(dataset, config$1) {
318
- if (typeof dataset.value === "string") dataset.typed = true;
319
- else _addIssue(this, "type", dataset, config$1);
320
- return dataset;
321
- }
322
- };
323
- }
324
- // @__NO_SIDE_EFFECTS__
325
- function unknown() {
326
- return {
327
- kind: "schema",
328
- type: "unknown",
329
- reference: unknown,
330
- expects: "unknown",
331
- async: false,
332
- get "~standard"() {
333
- return /* @__PURE__ */ _getStandardProps(this);
334
- },
335
- "~run"(dataset) {
336
- dataset.typed = true;
337
- return dataset;
338
- }
339
- };
340
- }
341
- // @__NO_SIDE_EFFECTS__
342
- function pipe(...pipe$1) {
343
- return {
344
- ...pipe$1[0],
345
- pipe: pipe$1,
346
- get "~standard"() {
347
- return /* @__PURE__ */ _getStandardProps(this);
348
- },
349
- "~run"(dataset, config$1) {
350
- for (const item of pipe$1) if (item.kind !== "metadata") {
351
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
352
- dataset.typed = false;
353
- break;
354
- }
355
- if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item["~run"](dataset, config$1);
356
- }
357
- return dataset;
358
- }
359
- };
360
- }
361
-
362
- // ../../packages/domain/dist/index.js
363
- function trimString(value) {
364
- return typeof value === "string" ? value.trim() : "";
365
- }
366
- var SYSTEM_ACTOR = { id: "system", kind: "system", provider: null };
367
- function serializeActor(actor) {
368
- return JSON.stringify({
369
- id: actor.id,
370
- kind: actor.kind,
371
- provider: actor.provider,
372
- ...actor.displayName !== void 0 ? { displayName: actor.displayName } : {}
373
- });
374
- }
375
- var SERIALIZED_SYSTEM_ACTOR = serializeActor(SYSTEM_ACTOR);
376
- var jsonObjectSchema = custom(
377
- (value) => typeof value === "object" && value !== null && !Array.isArray(value),
378
- "Expected object"
379
- );
380
- var instanceTurnConfigSchema = pipe(
381
- jsonObjectSchema,
382
- object({
383
- modelProfileId: optional(unknown())
384
- })
385
- );
386
- var strictInstanceTurnConfigsJsonSchema = pipe(
387
- string(),
388
- parseJson(),
389
- jsonObjectSchema,
390
- record(string(), instanceTurnConfigSchema)
391
- );
392
- var copiedUnknownRecordSchema = pipe(
393
- unknown(),
394
- check(isUnknownRecord, "Expected object"),
395
- record(string(), unknown())
396
- );
397
- function isUnknownRecord(value) {
398
- return typeof value === "object" && value !== null && !Array.isArray(value);
399
- }
400
-
401
5
  // src/launcher.ts
402
6
  import {
403
- SafeLaunchPreparationError
404
- } from "@leitwerk-dev/process-sdk";
7
+ createRepositoryChangeUiLauncher,
8
+ repositoryVisibilityCheck
9
+ } from "@leitwerk-dev/coding/repository-change-launch";
10
+ import { createGitSshPreparationCheck } from "@leitwerk-dev/git-ssh";
405
11
 
406
12
  // src/params.ts
407
13
  import {
408
14
  createRepositoryChangeParamsCodec,
409
- normalizeRepositoryChangeParamsInput,
410
- repositoryChangeParamsRecord
15
+ normalizeRepositoryIssueChangeParams
411
16
  } from "@leitwerk-dev/coding/repository-change-launch";
412
17
  function isIssueOrigin(params) {
413
18
  return params.origin === "issue";
414
19
  }
415
20
  var githubRepoChangeParamsCodec = createRepositoryChangeParamsCodec({
416
21
  normalize(value) {
417
- const shared = normalizeRepositoryChangeParamsInput(value, "GitHub Repo Change");
418
- const record3 = repositoryChangeParamsRecord(value, "GitHub Repo Change");
419
- const text = (name) => {
420
- const value2 = trimString(record3[name]);
421
- if (!value2) throw new Error(`GitHub Repo Change requires ${name}`);
422
- return value2;
423
- };
424
- const common = {
425
- ...shared,
426
- githubProfile: text("githubProfile"),
427
- sshCredentialRef: text("sshCredentialRef"),
428
- owner: text("owner"),
429
- repo: text("repo")
430
- };
431
- const origin = trimString(record3.origin);
432
- if (origin === "ui") {
433
- return {
434
- ...common,
435
- origin: "ui",
436
- issueNumber: null,
437
- issueUrl: null,
438
- triggerLabel: null,
439
- doneLabel: null
440
- };
441
- }
442
- if (origin && origin !== "issue") {
443
- throw new Error("GitHub Repo Change requires a valid origin");
444
- }
445
- if (typeof record3.issueNumber !== "number" || !Number.isInteger(record3.issueNumber) || record3.issueNumber <= 0)
446
- throw new Error("GitHub Repo Change requires issueNumber");
447
- return {
448
- ...common,
449
- origin: "issue",
450
- issueNumber: record3.issueNumber,
451
- issueUrl: text("issueUrl"),
452
- triggerLabel: text("triggerLabel"),
453
- doneLabel: text("doneLabel")
454
- };
22
+ return normalizeRepositoryIssueChangeParams(value, "GitHub Repo Change", [
23
+ "githubProfile",
24
+ "sshCredentialRef",
25
+ "owner",
26
+ "repo"
27
+ ]);
455
28
  }
456
29
  });
457
30
 
458
31
  // src/profile-bindings.ts
459
- function record2(value, label) {
460
- if (!value || typeof value !== "object" || Array.isArray(value))
461
- throw new Error(`${label} must be an object`);
462
- return value;
463
- }
464
- function field(value, fallback, label) {
465
- if (value === void 0) return fallback;
466
- if (typeof value !== "string" || !value.trim())
467
- throw new Error(`${label} must be a non-empty string`);
468
- return value.trim();
469
- }
32
+ import { parseRepositoryProfileBindings } from "@leitwerk-dev/coding/repository-change-launch";
470
33
  function parseProfileBindings(raw) {
471
- const config = raw === void 0 ? {} : record2(raw, "github-repo-change configuration");
472
- if (config.profile_bindings === void 0) return Object.freeze({});
473
- const mappings = record2(config.profile_bindings, "profile_bindings");
474
- const entries = Object.entries(mappings).map(([profile, value]) => {
475
- if (!profile.trim() || profile.trim() !== profile)
476
- throw new Error(
477
- "profile_bindings keys must be non-empty profile names without surrounding whitespace"
478
- );
479
- const mapping = record2(value, `profile_bindings.${profile}`);
480
- for (const key of Object.keys(mapping))
481
- if (key !== "ssh_credential_ref")
482
- throw new Error(`Unknown profile_bindings.${profile}.${key}`);
483
- return [
484
- profile,
485
- Object.freeze({
486
- sshCredentialRef: field(
487
- mapping.ssh_credential_ref,
488
- profile,
489
- `profile_bindings.${profile}.ssh_credential_ref`
490
- )
491
- })
492
- ];
34
+ return parseRepositoryProfileBindings(raw, "github-repo-change", {
35
+ sshCredentialRef: "ssh_credential_ref"
493
36
  });
494
- return Object.freeze(Object.fromEntries(entries));
495
37
  }
496
38
  function resolveProfileBinding(bindings, profile) {
497
39
  return Object.hasOwn(bindings, profile) ? { ...bindings[profile] } : { sshCredentialRef: profile };
@@ -552,56 +94,18 @@ function createGitHubRepoChangeLauncher() {
552
94
  if (!dependencies) throw new Error("GitHub repository launcher is not configured");
553
95
  return dependencies;
554
96
  }
555
- function sshPreparationCheck(access, params) {
556
- return {
557
- id: `ssh_${access}`,
558
- label: `Verify SSH ${access} access`,
559
- async run({ signal, logger }) {
560
- signal.throwIfAborted();
561
- const result = await requireDependencies().gitSsh.preflight({
562
- credentialRef: params.sshCredentialRef,
563
- repoLocator: params.repoLocator,
564
- baseBranch: params.baseBranch,
565
- requireWrite: access === "write"
566
- });
567
- signal.throwIfAborted();
568
- if (!result.ok) {
569
- logger.warn(`Git SSH ${result.access} preflight failed: ${result.detail}`);
570
- throw new SafeLaunchPreparationError(
571
- `SSH ${result.access} access failed: ${result.detail}`,
572
- `Authorize Git SSH profile '${params.sshCredentialRef}' for '${params.owner}/${params.repo}' with read/write access, then try again.`
573
- );
574
- }
575
- }
576
- };
577
- }
578
97
  function githubRepositoryPreparationChecks2(_input, { params }) {
579
98
  return [
580
- {
581
- id: "repository_visibility",
582
- label: "Check repository visibility",
583
- async run({ signal }) {
584
- signal.throwIfAborted();
585
- const repositoryName = `${params.owner}/${params.repo}`;
586
- const visible = (await repositories(params.githubProfile)).some(
587
- (candidate) => candidate.full_name === repositoryName
588
- );
589
- signal.throwIfAborted();
590
- if (!visible) {
591
- throw new SafeLaunchPreparationError(
592
- "Repository is not visible",
593
- "Grant the selected GitHub profile access to the repository, then try again."
594
- );
595
- }
596
- }
597
- },
598
- sshPreparationCheck("read", params),
599
- sshPreparationCheck("write", params)
99
+ repositoryVisibilityCheck(
100
+ "GitHub",
101
+ async () => (await repositories(params.githubProfile)).some(
102
+ (candidate) => candidate.full_name === `${params.owner}/${params.repo}`
103
+ )
104
+ ),
105
+ createGitSshPreparationCheck("read", params, () => requireDependencies().gitSsh),
106
+ createGitSshPreparationCheck("write", params, () => requireDependencies().gitSsh)
600
107
  ];
601
108
  }
602
- function validationError(fieldId, message, code = "required") {
603
- return { code, fieldId, message };
604
- }
605
109
  function resolveProfiles(profile) {
606
110
  const { github, gitSsh, profileBindings = {} } = requireDependencies();
607
111
  if (!(github.profiles?.() ?? []).includes(profile))
@@ -621,121 +125,19 @@ function createGitHubRepoChangeLauncher() {
621
125
  if (!(github.profiles?.() ?? []).includes(profile)) return [];
622
126
  return github.client(profile).listRepositories();
623
127
  }
624
- const githubRepoChangeUiLauncher2 = {
128
+ const githubRepoChangeUiLauncher2 = createRepositoryChangeUiLauncher({
625
129
  id: githubRepoChangeUiLauncherId,
626
- label: "GitHub Repo Change",
627
- description: "Plan, implement, review, and publish a GitHub change without a source issue",
628
- visibility: "ui",
629
- ui: {
630
- card: {
631
- title: "GitHub Repo Change",
632
- description: "Start a repository change and publish it as a GitHub pull request."
633
- },
634
- launchConfigSchema: {
635
- id: "github_repo_change_form",
636
- title: "GitHub Repo Change",
637
- fields: [
638
- {
639
- id: "githubProfile",
640
- label: "GitHub profile",
641
- kind: "select",
642
- required: true,
643
- description: "GitHub profile with server-configured CI and Git SSH access."
644
- },
645
- {
646
- id: "repository",
647
- label: "Repository",
648
- kind: "select",
649
- required: true,
650
- description: "Repository visible to the selected GitHub profile."
651
- },
652
- {
653
- id: "prompt",
654
- label: "Requested change",
655
- kind: "textarea",
656
- required: true,
657
- placeholder: "Describe the change to plan, implement, review, and publish."
658
- }
659
- ],
660
- submitLabel: "Start change"
661
- },
662
- resolveDefaults() {
663
- return {
664
- githubProfile: (requireDependencies().github.profiles?.() ?? [])[0] ?? "",
665
- repository: "",
666
- prompt: ""
667
- };
668
- },
669
- async resolveOptions(input) {
670
- const { github } = requireDependencies();
671
- const profile = trimString(input.githubProfile);
672
- return {
673
- githubProfile: (github.profiles?.() ?? []).map((value) => ({ value, label: value })),
674
- repository: (await repositories(profile)).map((repository) => ({
675
- value: repository.full_name,
676
- label: repository.full_name,
677
- description: repository.html_url
678
- }))
679
- };
680
- },
681
- preparationChecks: githubRepositoryPreparationChecks2,
682
- resolveRelaunchInput(previousInput) {
683
- return {
684
- githubProfile: trimString(previousInput.githubProfile),
685
- repository: trimString(previousInput.repository),
686
- prompt: trimString(previousInput.prompt)
687
- };
688
- },
689
- async resolveLaunchConfig(input) {
690
- const profile = trimString(input.githubProfile);
691
- const repositoryName = trimString(input.repository);
692
- const prompt = trimString(input.prompt);
693
- const errors = [];
694
- const invalid = (fieldId, message) => ({
695
- ok: false,
696
- errors: [validationError(fieldId, message, "custom_rule")]
697
- });
698
- const { github } = requireDependencies();
699
- if (!profile) errors.push(validationError("githubProfile", "GitHub profile is required"));
700
- else if (!(github.profiles?.() ?? []).includes(profile))
701
- errors.push(
702
- validationError("githubProfile", "GitHub profile is not available", "custom_rule")
703
- );
704
- if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
705
- if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
706
- if (errors.length > 0) return { ok: false, errors };
707
- const repository = (await repositories(profile)).find(
708
- (candidate) => candidate.full_name === repositoryName
709
- );
710
- if (!repository)
711
- return invalid(
712
- "repository",
713
- "Repository is not available to the selected GitHub profile"
714
- );
715
- let binding;
716
- try {
717
- binding = resolveProfiles(profile);
718
- } catch (error) {
719
- return invalid("githubProfile", error.message);
720
- }
721
- const gitIdentity = await resolveGitHubGitIdentity2(profile);
722
- const workBranch = buildAutoWorkBranchFromSeed(
723
- prompt,
724
- `${repository.ssh_url}:${repository.default_branch}`
725
- );
726
- const params = githubRepoChangeParams(repository, {
727
- ...binding,
728
- profile,
729
- prompt,
730
- workBranch
731
- });
732
- return {
733
- ok: true,
734
- launchConfig: githubRepoChangeLaunchConfig(params, prompt, gitIdentity)
735
- };
736
- }
737
- }
738
- };
130
+ provider: "GitHub",
131
+ providerId: "github",
132
+ assertConfigured: requireDependencies,
133
+ profiles: () => requireDependencies().github.profiles?.() ?? [],
134
+ repositories,
135
+ resolveProfiles,
136
+ resolveGitIdentity: resolveGitHubGitIdentity2,
137
+ params: githubRepoChangeParams,
138
+ launchConfig: githubRepoChangeLaunchConfig,
139
+ preparationChecks: githubRepositoryPreparationChecks2
140
+ });
739
141
  return {
740
142
  /** @public */
741
143
  configure: configureGitHubRepoChangeLauncher2,
@@ -754,13 +156,14 @@ function createGitHubRepoChangeLauncher() {
754
156
  import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
755
157
  import {
756
158
  createRepositoryChangePublication,
757
- publicationObject as object2,
758
- readPublicationState
159
+ publicationObject as object,
160
+ pullRequestPublicationCallbacks,
161
+ pullRequestPublicationSources,
162
+ readPublicationState,
163
+ reconcilePullRequestSourceIssue,
164
+ resolvePullRequestGitIdentity
759
165
  } from "@leitwerk-dev/coding/repository-change-publication";
760
- import {
761
- githubExternal,
762
- githubIssueWatcherSource
763
- } from "@leitwerk-dev/github";
166
+ import { githubExternal, githubIssueWatcherSource } from "@leitwerk-dev/github";
764
167
  var processId = "github_repo_change_process";
765
168
  var ids = {
766
169
  deliver: "deliver_change",
@@ -769,27 +172,6 @@ var ids = {
769
172
  operator: "ci_operator_action"
770
173
  };
771
174
  var remote = (state) => readPublicationState(state, "githubRepoChange");
772
- function requirePr(state) {
773
- const value = remote(state);
774
- if (!value.headSha || !value.prNumber || !value.prUrl)
775
- throw new Error("Pull request delivery state is incomplete");
776
- return { ...value, headSha: value.headSha, prNumber: value.prNumber, prUrl: value.prUrl };
777
- }
778
- var feedbackKey = (value) => `${value.kind}:${value.id}`;
779
- var callFor = (ctx) => (name, args) => ctx.callIntegrationTool(name, { projectKey: "repo", ...args });
780
- function requireIssueOrigin(params) {
781
- if (!isIssueOrigin(params)) throw new Error("GitHub source issue metadata is unavailable");
782
- return params;
783
- }
784
- function pinnedGitIdentity(ctx) {
785
- const project = ctx.projects.find((candidate2) => candidate2.key === "repo");
786
- const candidate = object2(project?.metadata)?.["leitwerk.gitIdentity"];
787
- const identity = object2(candidate);
788
- if (identity.provider !== "github" || identity.profile !== ctx.params.githubProfile || typeof identity.login !== "string" || !identity.login.trim() || typeof identity.name !== "string" || !identity.name.trim() || typeof identity.email !== "string" || !identity.email.trim()) {
789
- return null;
790
- }
791
- return identity;
792
- }
793
175
  var deliveryTools = [
794
176
  "github_get_pull_request",
795
177
  "github_add_pull_request_comment",
@@ -803,6 +185,14 @@ var deliveryTools = [
803
185
  "github_update_issue"
804
186
  ];
805
187
  function createGitHubRepoChangeProcess(launcher, docker) {
188
+ const sharedSources = pullRequestPublicationSources(
189
+ "github",
190
+ "GitHub",
191
+ githubExternal,
192
+ (params) => params.githubProfile,
193
+ (params) => isIssueOrigin(params) ? params : void 0
194
+ );
195
+ const { requirePr } = sharedSources;
806
196
  const failedPipeline = githubExternal.checks(
807
197
  ({ params, state }) => ({
808
198
  profile: params.githubProfile,
@@ -831,37 +221,10 @@ function createGitHubRepoChangeProcess(launcher, docker) {
831
221
  })),
832
222
  read: ({ event }) => ({
833
223
  kind: "conflict",
834
- conflict: object2(event).conflict
224
+ conflict: object(event).conflict
835
225
  })
836
226
  },
837
- {
838
- id: "github_feedback",
839
- kind: "feedback",
840
- label: "GitHub pull request feedback",
841
- source: githubExternal.pullRequestFeedback(({ params, state }) => ({
842
- profile: params.githubProfile,
843
- owner: params.owner,
844
- repo: params.repo,
845
- prNumber: requirePr(state).prNumber,
846
- conversationCursor: remote(state).conversationCursor,
847
- reviewCursor: remote(state).reviewCursor,
848
- inlineCursor: remote(state).inlineCursor,
849
- quietPeriodMs: 12e4,
850
- pollInterval: "30s"
851
- })),
852
- read: ({ state, event }) => {
853
- const value = object2(event);
854
- const cursors = object2(value.cursors);
855
- const current = remote(state);
856
- return {
857
- kind: "feedback",
858
- conversationCursor: Number(cursors.conversationCursor ?? current.conversationCursor),
859
- reviewCursor: Number(cursors.reviewCursor ?? current.reviewCursor),
860
- inlineCursor: Number(cursors.inlineCursor ?? current.inlineCursor),
861
- feedbackIds: value.feedbackIds ?? []
862
- };
863
- }
864
- },
227
+ sharedSources.feedback,
865
228
  {
866
229
  id: "github_failure_repair",
867
230
  operatorId: "github_failure_operator",
@@ -869,7 +232,7 @@ function createGitHubRepoChangeProcess(launcher, docker) {
869
232
  label: "Repair failed GitHub checks",
870
233
  source: failedPipeline,
871
234
  read: ({ state, event }) => {
872
- const checks = object2(object2(event).checks);
235
+ const checks = object(object(event).checks);
873
236
  const current = requirePr(state);
874
237
  if (checks.headSha !== current.headSha) throw new Error("Stale GitHub check evidence");
875
238
  const failed = Array.isArray(checks.failed) ? checks.failed : [];
@@ -879,48 +242,13 @@ function createGitHubRepoChangeProcess(launcher, docker) {
879
242
  number: 0,
880
243
  status: "failure",
881
244
  ...checks,
882
- evidenceKey: `${checks.headSha}:${failed.map((run) => object2(run).url).join(":")}`
245
+ evidenceKey: `${checks.headSha}:${failed.map((run) => object(run).url).join(":")}`
883
246
  }
884
247
  };
885
248
  }
886
249
  },
887
- ...["merged", "closed"].map((terminalOutcome) => ({
888
- id: `github_pr_${terminalOutcome}`,
889
- kind: "terminal",
890
- label: `GitHub pull request ${terminalOutcome}`,
891
- source: githubExternal.pullRequestTerminal(
892
- ({ params, state }) => ({
893
- profile: params.githubProfile,
894
- owner: params.owner,
895
- repo: params.repo,
896
- prNumber: requirePr(state).prNumber,
897
- terminalOutcome,
898
- pollInterval: "30s"
899
- })
900
- ),
901
- read: ({ event }) => ({
902
- kind: "terminal",
903
- request: object2(event).pullRequest
904
- })
905
- })),
906
- {
907
- id: "source_cancelled",
908
- kind: "cancelled",
909
- label: "Source issue cancelled",
910
- enabled: isIssueOrigin,
911
- source: githubExternal.issueCancelled(({ params }) => {
912
- const issue = requireIssueOrigin(params);
913
- return {
914
- profile: issue.githubProfile,
915
- owner: issue.owner,
916
- repo: issue.repo,
917
- issueNumber: issue.issueNumber,
918
- triggerLabel: issue.triggerLabel,
919
- pollInterval: "30s"
920
- };
921
- }),
922
- read: () => ({ kind: "cancelled" })
923
- }
250
+ ...sharedSources.terminal,
251
+ sharedSources.cancelled
924
252
  ];
925
253
  const publicationConfig = createRepositoryChangePublication({
926
254
  namespace: "githubRepoChange",
@@ -932,95 +260,17 @@ function createGitHubRepoChangeProcess(launcher, docker) {
932
260
  feedback: ["github_get_pull_request", "github_list_pull_request_feedback"],
933
261
  ci: ["github_get_ci_diagnostics"]
934
262
  },
935
- async identity(ctx) {
936
- return pinnedGitIdentity(ctx) ?? await callFor(ctx)("github_resolve_git_identity", {});
937
- },
938
- async reconcileTerminal(ctx, _current, pr) {
939
- const call = callFor(ctx);
940
- if (isIssueOrigin(ctx.params)) {
941
- const issue = await call("github_get_issue", {
942
- issueNumber: ctx.params.issueNumber
943
- });
944
- let labels = issue.labels.filter((label) => label.name !== ctx.params.triggerLabel).map((label) => label.name);
945
- if (pr.merged) {
946
- const done = await call("github_ensure_label", {
947
- name: ctx.params.doneLabel
948
- });
949
- labels = [.../* @__PURE__ */ new Set([...labels, done.name])];
950
- }
951
- await call("github_update_issue", {
952
- issueNumber: ctx.params.issueNumber,
953
- patch: { labels, ...pr.merged ? { state: "closed" } : {} },
954
- writeKey: `github:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`
955
- });
956
- await call("github_add_issue_comment", {
957
- issueNumber: ctx.params.issueNumber,
958
- 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.`,
959
- writeKey: `github:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`
960
- });
961
- }
962
- },
963
- async ensureRequest(ctx) {
964
- const call = callFor(ctx);
965
- const project = ctx.repo.get("repo");
966
- const issueOrigin = isIssueOrigin(ctx.params);
967
- const pr = await call("github_ensure_pull_request", {
968
- title: ctx.process.title ?? (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
969
- body: issueOrigin ? `Implements ${ctx.params.issueUrl}
970
-
971
- Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
972
- head: project.workBranch,
973
- base: project.baseBranch
974
- });
975
- if (!pr) throw new Error("GitHub pull request could not be created or found");
976
- return pr;
977
- },
978
- async linkIssue(ctx, current) {
979
- const call = callFor(ctx);
980
- if (isIssueOrigin(ctx.params)) {
981
- await call("github_add_issue_comment", {
982
- issueNumber: ctx.params.issueNumber,
983
- body: `Leitwerk opened pull request ${current.prUrl}.`,
984
- writeKey: `github:${ctx.process.id}:source-pr-link:${current.prNumber}`
985
- });
986
- }
987
- },
988
- async reply(ctx, current) {
989
- const call = callFor(ctx);
990
- for (const feedback of current.feedbackIds) {
991
- await call("github_reply_to_pull_request_feedback", {
992
- pullRequestNumber: current.prNumber,
993
- feedbackKind: feedback.kind,
994
- feedbackId: feedback.id,
995
- body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
996
- writeKey: `github:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`
997
- });
998
- }
999
- },
1000
- async acknowledge(ctx, current) {
1001
- const call = callFor(ctx);
1002
- for (const feedback of current.feedbackIds) {
1003
- if (feedback.kind === "review") continue;
1004
- await call("github_add_pull_request_feedback_reaction", {
1005
- pullRequestNumber: current.prNumber,
1006
- feedbackKind: feedback.kind,
1007
- feedbackId: feedback.id,
1008
- writeKey: `github:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`
1009
- });
1010
- }
1011
- },
1012
- async head(ctx, current) {
1013
- return (await callFor(ctx)("github_get_pull_request", {
1014
- pullRequestNumber: current.prNumber
1015
- })).head.sha;
1016
- },
1017
- async afterRebase(ctx, current) {
1018
- await callFor(ctx)("github_add_pull_request_comment", {
1019
- pullRequestNumber: current.prNumber,
1020
- body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
1021
- writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`
1022
- });
1023
- },
263
+ identity: (ctx) => resolvePullRequestGitIdentity(ctx, "github", ctx.params.githubProfile),
264
+ reconcileTerminal: reconcilePullRequestSourceIssue(
265
+ "github",
266
+ "name",
267
+ (params) => isIssueOrigin(params) ? params : void 0
268
+ ),
269
+ ...pullRequestPublicationCallbacks(
270
+ "github",
271
+ "GitHub",
272
+ (params) => isIssueOrigin(params) ? params : void 0
273
+ ),
1024
274
  commitMessage: (kind) => kind === "feedback" ? "fix: address GitHub review feedback" : "fix: repair GitHub checks",
1025
275
  prompt(kind, current) {
1026
276
  return kind === "feedback" ? `Address the unseen GitHub pull-request feedback batch for PR #${current.prNumber}. Feedback identifiers: ${JSON.stringify(current.feedbackIds)}. Inspect the current checkout and use GitHub 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 failed GitHub checks for request #${current.prNumber}, head ${current.headSha}. Use github_get_ci_diagnostics with pullRequestNumber and headSha to inspect failed check annotations and bounded Actions job 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.`;
@@ -1033,30 +283,7 @@ Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
1033
283
  description: "Launch a remote repository change for GitHub issues carrying the trigger label",
1034
284
  source: githubIssueWatcherSource,
1035
285
  preparationChecks: launcher.preparationChecks,
1036
- async resolveLaunchConfig({ profile, repository, issue, labels }) {
1037
- const issueNumber = issue.number;
1038
- const title = issue.title.trim();
1039
- const body = issue.body?.trim() ?? "";
1040
- const issueUrl = issue.html_url;
1041
- const binding = launcher.resolveProfiles(profile);
1042
- const gitIdentity = await launcher.resolveGitIdentity(profile);
1043
- const params = {
1044
- ...githubRepoChangeParams(repository, {
1045
- ...binding,
1046
- profile,
1047
- workBranch: `leitwerk/issue-${issueNumber}`,
1048
- prompt: `${title}${body ? `
1049
-
1050
- ${body}` : ""}`
1051
- }),
1052
- origin: "issue",
1053
- issueNumber,
1054
- issueUrl,
1055
- triggerLabel: labels.trigger,
1056
- doneLabel: labels.done
1057
- };
1058
- return githubRepoChangeLaunchConfig(params, title, gitIdentity);
1059
- }
286
+ resolveLaunchConfig: launcher.launcher.resolveIssueLaunchConfig
1060
287
  });
1061
288
  const definition = createRepositoryChangeProcess({
1062
289
  processId,