@leitwerk-dev/github 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.
Files changed (45) hide show
  1. package/README.md +113 -1
  2. package/dist/LICENSE +13 -0
  3. package/dist/authorization.d.ts +12 -0
  4. package/dist/authorization.d.ts.map +1 -0
  5. package/dist/binding.d.ts +4 -0
  6. package/dist/binding.d.ts.map +1 -0
  7. package/dist/capability.d.ts +8 -0
  8. package/dist/capability.d.ts.map +1 -0
  9. package/dist/chunk-PVE52UFH.js +318 -0
  10. package/dist/chunk-PVE52UFH.js.map +1 -0
  11. package/dist/client.d.ts +111 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/external.d.ts +85 -0
  14. package/dist/external.d.ts.map +1 -0
  15. package/dist/index.d.ts +18 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +809 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/issue-provider.d.ts +8 -0
  20. package/dist/issue-provider.d.ts.map +1 -0
  21. package/dist/issue-watcher.d.ts +19 -0
  22. package/dist/issue-watcher.d.ts.map +1 -0
  23. package/dist/poll-report.d.ts +22 -0
  24. package/dist/poll-report.d.ts.map +1 -0
  25. package/dist/provider.d.ts +6 -0
  26. package/dist/provider.d.ts.map +1 -0
  27. package/dist/testing.d.ts +81 -0
  28. package/dist/testing.d.ts.map +1 -0
  29. package/dist/testing.js +297 -0
  30. package/dist/testing.js.map +1 -0
  31. package/dist/tools.d.ts +5 -0
  32. package/dist/tools.d.ts.map +1 -0
  33. package/package.json +55 -14
  34. package/src/authorization.ts +54 -0
  35. package/src/binding.ts +6 -0
  36. package/src/capability.ts +13 -0
  37. package/src/client.ts +421 -0
  38. package/src/external.ts +139 -0
  39. package/src/index.ts +45 -0
  40. package/src/issue-provider.ts +278 -0
  41. package/src/issue-watcher.ts +30 -0
  42. package/src/poll-report.ts +47 -0
  43. package/src/provider.ts +216 -0
  44. package/src/testing.ts +384 -0
  45. package/src/tools.ts +304 -0
package/dist/index.js ADDED
@@ -0,0 +1,809 @@
1
+ import {
2
+ GitHubClient,
3
+ assertGitHubRepository,
4
+ parseGitHubProfiles
5
+ } from "./chunk-PVE52UFH.js";
6
+
7
+ // src/index.ts
8
+ import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
9
+
10
+ // src/capability.ts
11
+ import { createCapabilityToken } from "@leitwerk-dev/process-sdk";
12
+ var githubIntegration = createCapabilityToken(
13
+ "@leitwerk-private/github.integration"
14
+ );
15
+
16
+ // src/provider.ts
17
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
18
+ import { conflictEvidence, createConflictReporter } from "@leitwerk-dev/repository-rebase";
19
+ import { createPollSchedule as createPollSchedule2, emptyPollResult } from "@leitwerk-dev/watcher-utils";
20
+
21
+ // src/external.ts
22
+ import {
23
+ defineExternalActionSource
24
+ } from "@leitwerk-dev/process-sdk";
25
+ import { describeConflict } from "@leitwerk-dev/repository-rebase";
26
+ var GITHUB_PR_STATE_KIND = "@leitwerk-private/github.pr_state";
27
+ var GITHUB_RELEASE_KIND = "@leitwerk-private/github.release";
28
+ function describeGitHubEvent(event) {
29
+ const value = event;
30
+ if (value.kind === "merge_conflict") return describeConflict(event);
31
+ if (value.checks) {
32
+ const checks = value.checks;
33
+ return {
34
+ summary: `Checks ${checks.status} on ${checks.headSha}${checks.failed.length ? `: ${checks.failed.map((check) => check.name).join(", ")}` : ""}`,
35
+ links: checks.failed.flatMap(
36
+ (check, index) => check.url ? [{ id: `check-${index}`, label: check.name, url: check.url, kind: "pipeline" }] : []
37
+ )
38
+ };
39
+ }
40
+ return {
41
+ summary: value.kind === "merged" || value.kind === "closed" || value.pullRequest ? `PR #${value.pullRequest?.number} ${value.kind ?? (value.pullRequest?.merged ? "merged" : "closed")}` : value.kind === "feedback" ? "Pull request feedback received" : "GitHub event received"
42
+ };
43
+ }
44
+ var GITHUB_PR_TERMINAL_KIND = "@leitwerk-public/github.pr_terminal";
45
+ var GITHUB_PR_FEEDBACK_KIND = "@leitwerk-public/github.pr_feedback";
46
+ var GITHUB_ISSUE_CANCELLED_KIND = "@leitwerk-public/github.issue_cancelled";
47
+ var GITHUB_CHECKS_KIND = "@leitwerk-public/github.checks";
48
+ var githubExternal = {
49
+ checks: defineExternalActionSource({
50
+ kind: GITHUB_CHECKS_KIND,
51
+ describeEvent: describeGitHubEvent,
52
+ label: "GitHub Actions failures"
53
+ }),
54
+ issueCancelled: defineExternalActionSource({
55
+ kind: GITHUB_ISSUE_CANCELLED_KIND,
56
+ describeEvent: () => ({ summary: "Source issue cancelled" }),
57
+ label: "GitHub source issue cancelled",
58
+ description: "Fires when the source issue closes or loses its trigger label"
59
+ }),
60
+ pullRequestTerminal: defineExternalActionSource({
61
+ kind: GITHUB_PR_TERMINAL_KIND,
62
+ describeEvent: describeGitHubEvent,
63
+ label: "GitHub pull request merged or closed",
64
+ description: "Fires when the tracked pull request reaches a terminal state"
65
+ }),
66
+ pullRequestFeedback: defineExternalActionSource({
67
+ kind: GITHUB_PR_FEEDBACK_KIND,
68
+ describeEvent: () => ({ summary: "Pull request feedback received" }),
69
+ label: "GitHub pull request feedback",
70
+ description: "Fires after unseen human feedback has been quiet long enough to batch"
71
+ }),
72
+ releaseContaining: defineExternalActionSource({
73
+ kind: GITHUB_RELEASE_KIND,
74
+ label: "Published GitHub release",
75
+ description: "Fires when a published release contains the tracked merge commit"
76
+ }),
77
+ pullRequestState: defineExternalActionSource({
78
+ kind: GITHUB_PR_STATE_KIND,
79
+ describeEvent: describeGitHubEvent,
80
+ label: "GitHub pull request state",
81
+ description: "Fires for failed or successful checks, review feedback, and terminal PR state"
82
+ })
83
+ };
84
+
85
+ // src/issue-provider.ts
86
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
87
+ import {
88
+ matchesRepository as matchesConfiguredRepository,
89
+ parseRepositoryFeedbackConfig as parseFeedbackConfig,
90
+ parseRepositoryIssueCancelledConfig as parseIssueCancelledConfig,
91
+ parseRepositoryPullRequestConfig as parsePrConfig,
92
+ repositoryFeedbackBatch
93
+ } from "@leitwerk-dev/process-sdk";
94
+ import { sameSubscription as sameSubscription2 } from "@leitwerk-dev/repository-rebase";
95
+ import { createPollSchedule } from "@leitwerk-dev/watcher-utils";
96
+
97
+ // src/issue-watcher.ts
98
+ import {
99
+ defineProcessWatcherSource,
100
+ parseRepositoryIssueWatcherConfig,
101
+ presentRepositoryIssueWatcherConfig
102
+ } from "@leitwerk-dev/process-sdk";
103
+ var githubIssueWatcherSource = defineProcessWatcherSource({
104
+ id: "@leitwerk-public/github.issue",
105
+ label: "GitHub issue",
106
+ parseConfig: (raw) => parseRepositoryIssueWatcherConfig(raw, "github_issue", true),
107
+ presentConfig: presentRepositoryIssueWatcherConfig
108
+ });
109
+
110
+ // src/poll-report.ts
111
+ import {
112
+ createExternalSourcePollReporter
113
+ } from "@leitwerk-dev/process-sdk";
114
+ import { sameSubscription } from "@leitwerk-dev/repository-rebase";
115
+ function githubPollReporter(sources, result) {
116
+ const report = createExternalSourcePollReporter(sources, result, { forwardGeneration: true });
117
+ const current = (armed) => [
118
+ GITHUB_CHECKS_KIND,
119
+ GITHUB_PR_STATE_KIND,
120
+ GITHUB_PR_TERMINAL_KIND,
121
+ GITHUB_PR_FEEDBACK_KIND,
122
+ GITHUB_ISSUE_CANCELLED_KIND,
123
+ GITHUB_RELEASE_KIND
124
+ ].some((kind) => sources.listArmed(kind).some((value) => sameSubscription(armed, value)));
125
+ return {
126
+ ...report,
127
+ async fire(armed, event, mergeKey) {
128
+ if (!current(armed)) return false;
129
+ return report.fire(armed, event, mergeKey);
130
+ },
131
+ observe(armed, input) {
132
+ if (current(armed)) return report.observe(armed, input);
133
+ }
134
+ };
135
+ }
136
+
137
+ // src/issue-provider.ts
138
+ function hasLabel(issue, label) {
139
+ return issue.labels.some((candidate) => candidate.name === label);
140
+ }
141
+ function externalId(repo, issue) {
142
+ return `github:${repo.full_name}#${issue.number}`;
143
+ }
144
+ function createGitHubIssuePolling(deps, integration, options = {}) {
145
+ const now = options.now ?? Date.now;
146
+ const due = createPollSchedule(now);
147
+ async function discover(watcher, result) {
148
+ const config = watcher.config;
149
+ const client = integration.client(config.profile);
150
+ for (const repo of await client.listRepositories()) {
151
+ if (!matchesConfiguredRepository(config, repo)) continue;
152
+ for (const issue of await client.listOpenIssues(repo.owner.login, repo.name)) {
153
+ if (!hasLabel(issue, config.labels.trigger) || hasLabel(issue, config.labels.done))
154
+ continue;
155
+ const id = externalId(repo, issue);
156
+ try {
157
+ if (deps.processes.listAll().some((process) => process.externalId === id)) {
158
+ result.skipped.push(id);
159
+ continue;
160
+ }
161
+ const authorized = await client.authorizedTrigger(
162
+ repo.owner.login,
163
+ repo.name,
164
+ issue.number,
165
+ config.labels.trigger,
166
+ config.labels.done
167
+ );
168
+ if (!authorized) {
169
+ result.skipped.push(`${id}:unauthorized`);
170
+ continue;
171
+ }
172
+ const event = {
173
+ profile: config.profile,
174
+ repository: repo,
175
+ issue: authorized.issue,
176
+ authorization: {
177
+ actor: authorized.actor,
178
+ eventId: authorized.eventId
179
+ },
180
+ labels: config.labels
181
+ };
182
+ const guardedWatcher = {
183
+ ...watcher,
184
+ async resolveLaunchAttempt(...args) {
185
+ const attempt = await watcher.resolveLaunchAttempt(...args);
186
+ if (!attempt) return null;
187
+ return {
188
+ ...attempt,
189
+ preparationChecks: [
190
+ ...attempt.preparationChecks,
191
+ {
192
+ id: "github-trigger-authorization",
193
+ label: "Check GitHub trigger authorization",
194
+ async run() {
195
+ const rechecked = await client.authorizedTrigger(
196
+ repo.owner.login,
197
+ repo.name,
198
+ issue.number,
199
+ config.labels.trigger,
200
+ config.labels.done
201
+ );
202
+ if (!rechecked || rechecked.eventId !== authorized.eventId || rechecked.actor !== authorized.actor)
203
+ throw new Error("GitHub trigger authorization changed before launch");
204
+ }
205
+ }
206
+ ]
207
+ };
208
+ }
209
+ };
210
+ const launched = await deps.launchRuns.startWatcher(guardedWatcher, event, {
211
+ idempotencyKey: id
212
+ });
213
+ if (launched.error) result.errors.push(`${id}:launch_failed:${launched.error}`);
214
+ else if (launched.process) result.created.push(id);
215
+ else result.skipped.push(id);
216
+ } catch (error) {
217
+ result.errors.push(
218
+ `${id}:${error instanceof Error ? error.message : "discovery_failed"}`
219
+ );
220
+ }
221
+ }
222
+ }
223
+ }
224
+ async function pollExternal(result) {
225
+ const report = githubPollReporter(deps.externalSources, result);
226
+ const terminalArmings = deps.externalSources.listArmed(GITHUB_PR_TERMINAL_KIND);
227
+ const terminalInstances = /* @__PURE__ */ new Set();
228
+ async function poll(kind, parse2, read) {
229
+ const armings = kind === GITHUB_PR_TERMINAL_KIND ? terminalArmings : deps.externalSources.listArmed(kind);
230
+ for (const armed of armings) {
231
+ if (kind !== GITHUB_PR_TERMINAL_KIND && terminalInstances.has(armed.instanceId)) continue;
232
+ const config = parse2(armed.resolved);
233
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
234
+ if (!config || !due(key, config.pollInterval ?? "30s") || config.disabled) continue;
235
+ try {
236
+ await read(config, armed);
237
+ } catch (error) {
238
+ await report.observe(armed, {
239
+ refreshError: error instanceof Error ? error.message : "GitHub refresh failed"
240
+ });
241
+ const fallback = kind === GITHUB_CHECKS_KIND ? "checks_failed" : "poll_failed";
242
+ result.errors.push(`${armed.id}:${error instanceof Error ? error.message : fallback}`);
243
+ }
244
+ }
245
+ }
246
+ await poll(GITHUB_PR_TERMINAL_KIND, parsePrConfig, async (config, armed) => {
247
+ const pr = await integration.client(config.profile).getPullRequest(config.owner, config.repo, config.prNumber);
248
+ if (!pr.merged && pr.state !== "closed") return;
249
+ if (!deps.externalSources.listArmed(GITHUB_PR_TERMINAL_KIND).some((current) => sameSubscription2(armed, current)))
250
+ return;
251
+ terminalInstances.add(armed.instanceId);
252
+ const outcome = pr.merged ? "merged" : "closed";
253
+ if (config.terminalOutcome && config.terminalOutcome !== outcome) return;
254
+ await report.fire(armed, { pullRequest: pr }, `${pr.number}:${outcome}`);
255
+ });
256
+ await poll(
257
+ GITHUB_CHECKS_KIND,
258
+ (value) => ({ pollInterval: "30s", config: asUnknownRecord(value) ?? {} }),
259
+ async ({ config }, armed) => {
260
+ const client = integration.client(String(config.profile));
261
+ const pr = await client.getPullRequest(
262
+ String(config.owner),
263
+ String(config.repo),
264
+ Number(config.prNumber)
265
+ );
266
+ if (pr.state !== "open" || pr.head.sha !== config.headSha) return;
267
+ const checks = await client.getCheckSummary(
268
+ String(config.owner),
269
+ String(config.repo),
270
+ String(config.headSha)
271
+ );
272
+ if (checks.headSha !== config.headSha) return;
273
+ const refreshed = await client.getPullRequest(
274
+ String(config.owner),
275
+ String(config.repo),
276
+ Number(config.prNumber)
277
+ );
278
+ if (refreshed.state !== "open" || refreshed.merged || refreshed.head.sha !== checks.headSha)
279
+ return;
280
+ await report.observe(armed, {
281
+ observation: {
282
+ ...describeGitHubEvent({ checks }),
283
+ observedAt: new Date(now()).toISOString(),
284
+ subject: `${config.owner}/${config.repo}#${config.prNumber}`,
285
+ revision: checks.headSha
286
+ }
287
+ });
288
+ if (checks.status !== "failure") return;
289
+ await report.fire(
290
+ armed,
291
+ { checks },
292
+ `${checks.headSha}:${checks.failed.map((run) => run.url).join(":")}`
293
+ );
294
+ }
295
+ );
296
+ await poll(GITHUB_ISSUE_CANCELLED_KIND, parseIssueCancelledConfig, async (config, armed) => {
297
+ const issue = await integration.client(config.profile).getIssue(config.owner, config.repo, config.issueNumber);
298
+ const reason = issue.state === "closed" ? "issue_closed" : hasLabel(issue, config.triggerLabel) ? null : "trigger_label_removed";
299
+ if (!reason) return;
300
+ const terminal = terminalArmings.filter((candidate) => candidate.instanceId === armed.instanceId).map((candidate) => parsePrConfig(candidate.resolved)).find((candidate) => candidate && !candidate.disabled);
301
+ if (terminal) {
302
+ const pr = await integration.client(terminal.profile).getPullRequest(terminal.owner, terminal.repo, terminal.prNumber);
303
+ if (pr.merged || pr.state === "closed") {
304
+ terminalInstances.add(armed.instanceId);
305
+ return;
306
+ }
307
+ }
308
+ await report.fire(armed, { issue, reason }, `${issue.number}:${reason}`);
309
+ });
310
+ await poll(GITHUB_PR_FEEDBACK_KIND, parseFeedbackConfig, async (config, armed) => {
311
+ const client = integration.client(config.profile);
312
+ const pr = await client.getPullRequest(config.owner, config.repo, config.prNumber);
313
+ if (pr.merged || pr.state !== "open") return;
314
+ const unseen = (await client.listActionablePullRequestFeedback(config.owner, config.repo, config.prNumber)).filter((item) => item.id > config[`${item.kind}Cursor`]);
315
+ const batch = repositoryFeedbackBatch(unseen, config, now());
316
+ if (batch) await report.fire(armed, batch.event, batch.mergeKey);
317
+ });
318
+ }
319
+ return async (result) => {
320
+ const watchers = deps.processWatchers?.listBySource(githubIssueWatcherSource) ?? [];
321
+ for (const watcher of watchers) {
322
+ if (!watcher.enabled || !due(`${watcher.processId}:${watcher.watcherId}`, watcher.config.pollInterval))
323
+ continue;
324
+ try {
325
+ await discover(watcher, result);
326
+ } catch (error) {
327
+ result.errors.push(
328
+ `${watcher.processId}:${watcher.watcherId}:${error instanceof Error ? error.message : "discovery_failed"}`
329
+ );
330
+ }
331
+ }
332
+ await pollExternal(result);
333
+ };
334
+ }
335
+
336
+ // src/provider.ts
337
+ function parse(value) {
338
+ const config = asUnknownRecord2(value) ?? {};
339
+ if (["profile", "owner", "repo", "headSha"].some(
340
+ (key) => typeof config[key] !== "string" || !config[key].trim()
341
+ ) || typeof config.prNumber !== "number")
342
+ return null;
343
+ return {
344
+ profile: config.profile,
345
+ owner: config.owner,
346
+ repo: config.repo,
347
+ prNumber: config.prNumber,
348
+ headSha: config.headSha,
349
+ lastConflictKey: typeof config.lastConflictKey === "string" ? config.lastConflictKey : null,
350
+ feedbackCursor: typeof config.feedbackCursor === "number" ? config.feedbackCursor : 0,
351
+ pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s",
352
+ disabled: config.disabled === true,
353
+ eventKinds: Array.isArray(config.eventKinds) ? config.eventKinds.filter(
354
+ (value2) => ["checks", "feedback", "merged", "closed", "merge_conflict"].includes(String(value2))
355
+ ) : void 0,
356
+ checkStatuses: Array.isArray(config.checkStatuses) ? config.checkStatuses.filter(
357
+ (value2) => ["pending", "success", "failure"].includes(String(value2))
358
+ ) : void 0
359
+ };
360
+ }
361
+ function createGitHubProvider(deps, integration, options = {}) {
362
+ const due = createPollSchedule2();
363
+ const pollIssues = createGitHubIssuePolling(deps, integration, options);
364
+ const reportConflict = createConflictReporter(deps.externalSources, GITHUB_PR_STATE_KIND);
365
+ return deps.polling.create({
366
+ id: "github",
367
+ pollInterval: () => "5s",
368
+ isEnabled: () => true,
369
+ defaultIntervalMs: 5e3,
370
+ async pollOnce() {
371
+ const result = emptyPollResult();
372
+ const report = githubPollReporter(deps.externalSources, result);
373
+ await pollIssues(result);
374
+ await report.poll(GITHUB_PR_STATE_KIND, async (armed) => {
375
+ const config = parse(armed.resolved);
376
+ if (!config) {
377
+ result.errors.push(`${armed.id}:invalid_config`);
378
+ return;
379
+ }
380
+ if (config.disabled) return;
381
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
382
+ const now = options.now?.() ?? Date.now();
383
+ if (!due(key, config.pollInterval, now)) return;
384
+ try {
385
+ const client = integration.client(config.profile);
386
+ const pr = await client.getPullRequest(config.owner, config.repo, config.prNumber);
387
+ if (!config.eventKinds || config.eventKinds.includes("merge_conflict")) {
388
+ const conflict = conflictEvidence(config, pr, "github");
389
+ if (conflict?.reason === "behind") {
390
+ const branch = await client.getCommit(config.owner, config.repo, conflict.baseBranch);
391
+ conflict.baseSha = branch.sha;
392
+ }
393
+ if (await reportConflict(report, armed, conflict, config.lastConflictKey, {
394
+ summary: `PR #${pr.number} mergeability: ${pr.mergeable == null ? "unresolved" : pr.mergeable_state ?? String(pr.mergeable)}`,
395
+ observedAt: new Date(now).toISOString(),
396
+ subject: `${config.owner}/${config.repo}#${pr.number}`,
397
+ revision: `${pr.head.sha}:${conflict?.baseSha ?? pr.base.sha}`
398
+ }))
399
+ return;
400
+ if (config.eventKinds?.length === 1) return;
401
+ }
402
+ let event = null;
403
+ let mergeKey = "";
404
+ if (pr.merged || pr.state === "closed") {
405
+ event = {
406
+ kind: pr.merged ? "merged" : "closed",
407
+ pullRequest: pr
408
+ };
409
+ mergeKey = `terminal:${pr.number}:${pr.merged}`;
410
+ } else {
411
+ if (pr.head.sha !== config.headSha) return;
412
+ const readsFeedback = !config.eventKinds || config.eventKinds.includes("feedback");
413
+ const readsChecks = !config.eventKinds || config.eventKinds.includes("checks");
414
+ const [feedback, checks] = await Promise.all([
415
+ readsFeedback ? client.listActionablePullRequestFeedback(
416
+ config.owner,
417
+ config.repo,
418
+ config.prNumber
419
+ ) : Promise.resolve([]),
420
+ readsChecks || deps.externalSources.observe && armed.generation ? client.getCheckSummary(config.owner, config.repo, config.headSha).catch(async (error) => {
421
+ await report.observe(armed, {
422
+ refreshError: error instanceof Error ? error.message : "Checks refresh failed"
423
+ });
424
+ if (readsChecks) throw error;
425
+ return null;
426
+ }) : Promise.resolve(null)
427
+ ]);
428
+ if (checks && checks.headSha !== config.headSha) return;
429
+ const refreshed = await client.getPullRequest(
430
+ config.owner,
431
+ config.repo,
432
+ config.prNumber
433
+ );
434
+ if (refreshed.state !== "open" || refreshed.merged || refreshed.head.sha !== config.headSha)
435
+ return;
436
+ if (checks && deps.externalSources.observe && armed.generation) {
437
+ const description = describeGitHubEvent({ kind: "checks", checks });
438
+ await report.observe(armed, {
439
+ observation: {
440
+ ...description,
441
+ observedAt: new Date(now).toISOString(),
442
+ subject: `${config.owner}/${config.repo}#${config.prNumber}`,
443
+ revision: checks.headSha
444
+ }
445
+ });
446
+ }
447
+ const unseen = feedback.filter(
448
+ (item) => item.id > config.feedbackCursor && item.author !== client.profile.botLogin
449
+ );
450
+ if (unseen.length) {
451
+ const feedbackCursor = Math.max(...unseen.map((item) => item.id));
452
+ event = { kind: "feedback", feedback, feedbackCursor };
453
+ mergeKey = `feedback:${feedbackCursor}`;
454
+ } else if (readsChecks && checks && checks.status !== "pending") {
455
+ event = { kind: "checks", checks };
456
+ mergeKey = `checks:${checks.headSha}:${checks.status}`;
457
+ }
458
+ }
459
+ if (!event || config.eventKinds && !config.eventKinds.includes(
460
+ String(event.kind)
461
+ ) || event.kind === "checks" && config.checkStatuses && !config.checkStatuses.includes(
462
+ event.checks.status
463
+ ))
464
+ return;
465
+ await report.fire(armed, event, mergeKey);
466
+ } catch (error) {
467
+ await report.observe(armed, {
468
+ refreshError: error instanceof Error ? error.message : "PR refresh failed"
469
+ });
470
+ throw error;
471
+ }
472
+ });
473
+ await report.poll(GITHUB_RELEASE_KIND, async (armed) => {
474
+ const config = asUnknownRecord2(armed.resolved) ?? {};
475
+ if (typeof config.profile !== "string" || typeof config.owner !== "string" || typeof config.repo !== "string" || typeof config.mergeSha !== "string")
476
+ return;
477
+ if (config.disabled === true) return;
478
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
479
+ const now = options.now?.() ?? Date.now();
480
+ if (!due(key, typeof config.pollInterval === "string" ? config.pollInterval : "30s", now))
481
+ return;
482
+ const client = integration.client(config.profile);
483
+ for (const release of await client.listReleases(config.owner, config.repo)) {
484
+ if (release.draft || release.prerelease) continue;
485
+ const commit = await client.getCommit(config.owner, config.repo, release.tag_name);
486
+ if (!await client.isAncestor(config.owner, config.repo, config.mergeSha, commit.sha))
487
+ continue;
488
+ await report.fire(
489
+ armed,
490
+ { release, commitSha: commit.sha },
491
+ `${release.id}:${commit.sha}`
492
+ );
493
+ break;
494
+ }
495
+ });
496
+ return result;
497
+ }
498
+ });
499
+ }
500
+
501
+ // src/tools.ts
502
+ import {
503
+ createWriteIdentity,
504
+ ensureWrite,
505
+ recordWriteIfMissing
506
+ } from "@leitwerk-dev/external-writes";
507
+ import {
508
+ numberArg,
509
+ objectArg,
510
+ projectParameters,
511
+ stringArg
512
+ } from "@leitwerk-dev/process-sdk";
513
+
514
+ // src/binding.ts
515
+ import { resolveRepositoryProjectBinding } from "@leitwerk-dev/process-sdk";
516
+ var resolveGitHubProjectBinding = (ctx) => resolveRepositoryProjectBinding(ctx, "github");
517
+
518
+ // src/tools.ts
519
+ var object = (value) => objectArg(value, "Expected an object");
520
+ async function reconcileComment(comments, marker, body, post) {
521
+ const existing = (await comments).find((comment) => String(comment.body).includes(marker));
522
+ return existing ?? post(`${body()}
523
+
524
+ ${marker}`);
525
+ }
526
+ function registerGitHubTools(api, integration, writes) {
527
+ const target = (ctx) => {
528
+ const binding = resolveGitHubProjectBinding(ctx);
529
+ assertGitHubRepository(
530
+ integration.client(binding.profile).profile,
531
+ binding.owner,
532
+ binding.repo
533
+ );
534
+ return binding;
535
+ };
536
+ api.tool({
537
+ name: "github_resolve_git_identity",
538
+ description: "Resolve the configured GitHub Git identity",
539
+ parameters: {
540
+ type: "object",
541
+ properties: { projectKey: { type: "string" } },
542
+ required: ["projectKey"]
543
+ },
544
+ async execute(ctx) {
545
+ const t = target(ctx);
546
+ return integration.client(t.profile).resolveGitIdentity(t.profile);
547
+ }
548
+ });
549
+ for (const name of [
550
+ "github_ensure_label",
551
+ "github_update_issue",
552
+ "github_add_issue_comment",
553
+ "github_add_pull_request_feedback_reaction",
554
+ "github_reply_to_pull_request_feedback"
555
+ ]) {
556
+ api.tool({
557
+ name,
558
+ description: "Reconcile GitHub delivery in the current process project",
559
+ parameters: {
560
+ type: "object",
561
+ properties: {
562
+ projectKey: { type: "string" },
563
+ issueNumber: { type: "integer" },
564
+ pullRequestNumber: { type: "integer" },
565
+ name: { type: "string" },
566
+ patch: { type: "object" },
567
+ body: { type: "string" },
568
+ feedbackKind: { type: "string" },
569
+ feedbackId: { type: "integer" },
570
+ writeKey: { type: "string" }
571
+ },
572
+ required: ["projectKey"]
573
+ },
574
+ async execute(ctx, args) {
575
+ const input = object(args);
576
+ const t = target(ctx);
577
+ const client = integration.client(t.profile);
578
+ const key = typeof input.writeKey === "string" ? stringArg(input, "writeKey") : ctx.idempotencyKey;
579
+ const marker = `<!-- leitwerk-write:${ctx.process.id}:${key} -->`;
580
+ let value;
581
+ const result = await ensureWrite(
582
+ writes,
583
+ ctx.process.id,
584
+ createWriteIdentity(name, key),
585
+ async () => {
586
+ if (name === "github_ensure_label")
587
+ value = await client.ensureLabel(t.owner, t.repo, stringArg(input, "name"));
588
+ else if (name === "github_update_issue") {
589
+ const issueNumber = numberArg(input, "issueNumber");
590
+ const current = await client.getIssue(t.owner, t.repo, issueNumber);
591
+ const patch = object(input.patch);
592
+ const same = Object.entries(patch).every(
593
+ ([key2, expected]) => JSON.stringify(
594
+ key2 === "labels" ? current.labels.map((label) => label.name).sort() : object(current)[key2]
595
+ ) === JSON.stringify(
596
+ key2 === "labels" && Array.isArray(expected) ? [...expected].sort() : expected
597
+ )
598
+ );
599
+ value = same ? current : await client.updateIssue(t.owner, t.repo, issueNumber, patch);
600
+ } else if (name === "github_add_pull_request_feedback_reaction") {
601
+ const kind = stringArg(input, "feedbackKind");
602
+ const id = numberArg(input, "feedbackId");
603
+ const reactions = await client.listFeedbackReactions(t.owner, t.repo, kind, id);
604
+ value = reactions.find(
605
+ (reaction) => reaction.content === "eyes" && reaction.user.login.toLowerCase() === client.profile.botLogin.toLowerCase()
606
+ ) ?? await client.addFeedbackReaction(t.owner, t.repo, kind, id);
607
+ } else {
608
+ const issueNumber = numberArg(
609
+ { issueNumber: input.issueNumber ?? input.pullRequestNumber },
610
+ "issueNumber"
611
+ );
612
+ value = await reconcileComment(
613
+ name === "github_reply_to_pull_request_feedback" ? client.listFeedbackReplies(
614
+ t.owner,
615
+ t.repo,
616
+ issueNumber,
617
+ stringArg(input, "feedbackKind")
618
+ ) : client.listIssueComments(t.owner, t.repo, issueNumber),
619
+ marker,
620
+ () => stringArg(input, "body"),
621
+ (body) => name === "github_add_issue_comment" ? client.addIssueComment(t.owner, t.repo, issueNumber, body) : client.replyFeedback(
622
+ t.owner,
623
+ t.repo,
624
+ issueNumber,
625
+ stringArg(input, "feedbackKind"),
626
+ numberArg(input, "feedbackId"),
627
+ body
628
+ )
629
+ );
630
+ }
631
+ return { value };
632
+ }
633
+ );
634
+ if (name === "github_ensure_label") return { name: stringArg(input, "name") };
635
+ return value ?? result;
636
+ }
637
+ });
638
+ }
639
+ api.tool({
640
+ name: "github_ensure_pull_request",
641
+ description: "Create a GitHub pull request unless the branch pair already has one",
642
+ parameters: projectParameters({
643
+ title: { type: "string" },
644
+ body: { type: "string" },
645
+ head: { type: "string" },
646
+ base: { type: "string" }
647
+ }),
648
+ async execute(ctx, input) {
649
+ const t = target(ctx);
650
+ const client = integration.client(t.profile);
651
+ const head = stringArg(input, "head");
652
+ const base = stringArg(input, "base");
653
+ if (head !== ctx.project?.workBranch || base !== ctx.project?.baseBranch)
654
+ throw new Error("Pull request branches must match the process project");
655
+ const find = async () => (await client.listPullRequests(t.owner, t.repo, "all")).find(
656
+ (candidate) => candidate.head.ref === head && candidate.base.ref === base
657
+ ) ?? null;
658
+ let pr = await find();
659
+ const identity = createWriteIdentity("github.ensure_pr", ctx.idempotencyKey);
660
+ if (!pr) {
661
+ try {
662
+ await ensureWrite(writes, ctx.process.id, identity, async () => {
663
+ pr = await client.createPullRequest(t.owner, t.repo, {
664
+ title: stringArg(input, "title"),
665
+ body: stringArg(input, "body"),
666
+ head,
667
+ base
668
+ });
669
+ return { number: pr.number, url: pr.html_url };
670
+ });
671
+ } catch (error) {
672
+ pr = await find();
673
+ if (!pr) throw error;
674
+ }
675
+ pr ??= await find();
676
+ }
677
+ if (!pr) throw new Error("GitHub pull request creation could not be reconciled");
678
+ recordWriteIfMissing(writes, ctx.process.id, identity, {
679
+ number: pr.number,
680
+ url: pr.html_url
681
+ });
682
+ return pr;
683
+ }
684
+ });
685
+ for (const [name, description, numberName, method] of [
686
+ [
687
+ "github_get_issue",
688
+ "Read a GitHub issue in the current process project",
689
+ "issueNumber",
690
+ "getIssue"
691
+ ],
692
+ [
693
+ "github_get_pull_request",
694
+ "Read a GitHub pull request in the current process project",
695
+ "pullRequestNumber",
696
+ "getPullRequest"
697
+ ],
698
+ [
699
+ "github_list_pull_request_feedback",
700
+ "Read GitHub pull request conversation, reviews, and inline comments",
701
+ "pullRequestNumber",
702
+ "listActionablePullRequestFeedback"
703
+ ]
704
+ ]) {
705
+ api.tool({
706
+ name,
707
+ description,
708
+ parameters: projectParameters({ [numberName]: { type: "integer" } }),
709
+ async execute(ctx, input) {
710
+ const t = target(ctx);
711
+ return integration.client(t.profile)[method](t.owner, t.repo, numberArg(input, numberName), ctx.signal);
712
+ }
713
+ });
714
+ }
715
+ api.tool({
716
+ name: "github_get_checks",
717
+ description: "Read GitHub Actions check runs for a commit",
718
+ parameters: projectParameters({ headSha: { type: "string" } }),
719
+ async execute(ctx, input) {
720
+ const t = target(ctx);
721
+ return integration.client(t.profile).getCheckSummary(t.owner, t.repo, stringArg(input, "headSha"));
722
+ }
723
+ });
724
+ for (const definition of [
725
+ { name: "github_add_pull_request_comment", update: false },
726
+ { name: "github_update_pull_request", update: true }
727
+ ]) {
728
+ api.tool({
729
+ name: definition.name,
730
+ description: definition.update ? "Update a GitHub pull request" : "Comment on a GitHub pull request",
731
+ parameters: projectParameters(
732
+ {
733
+ pullRequestNumber: { type: "integer" },
734
+ ...definition.update ? { patch: { type: "object" } } : { body: { type: "string" }, writeKey: { type: "string" } }
735
+ },
736
+ ["pullRequestNumber", definition.update ? "patch" : "body"]
737
+ ),
738
+ async execute(ctx, input) {
739
+ const t = target(ctx);
740
+ const pr = numberArg(input, "pullRequestNumber");
741
+ const key = !definition.update && typeof input.writeKey === "string" ? stringArg(input, "writeKey") : ctx.idempotencyKey;
742
+ return ensureWrite(
743
+ writes,
744
+ ctx.process.id,
745
+ createWriteIdentity(definition.update ? "github.update_pr" : "github.comment", key),
746
+ async () => {
747
+ if (definition.update)
748
+ await integration.client(t.profile).updatePullRequest(t.owner, t.repo, pr, object(input.patch), ctx.signal);
749
+ else {
750
+ const client = integration.client(t.profile);
751
+ await reconcileComment(
752
+ client.listIssueComments(t.owner, t.repo, pr, ctx.signal),
753
+ `<!-- leitwerk-write:${ctx.process.id}:${key} -->`,
754
+ () => stringArg(input, "body"),
755
+ (body) => client.addIssueComment(t.owner, t.repo, pr, body, ctx.signal)
756
+ );
757
+ }
758
+ return { owner: t.owner, repo: t.repo, pullRequestNumber: pr };
759
+ }
760
+ );
761
+ }
762
+ });
763
+ }
764
+ }
765
+
766
+ // src/index.ts
767
+ var manifest = { id: "github", version: "0.1.9" };
768
+ var extension = {
769
+ manifest,
770
+ setupServer(api, config) {
771
+ const profiles = parseGitHubProfiles(config);
772
+ const integration = {
773
+ client(profile) {
774
+ const value = profiles.get(profile);
775
+ if (!value) throw new Error(`Unknown GitHub profile '${profile}'`);
776
+ return new GitHubClient(value);
777
+ }
778
+ };
779
+ setupGitHubIntegration(api, integration);
780
+ }
781
+ };
782
+ var index_default = extension;
783
+ function setupGitHubIntegration(api, integration, options = {}) {
784
+ api.provide(githubIntegration, integration);
785
+ const deps = api.get(coreHostCapabilities.serverSetup);
786
+ if (!deps || Array.isArray(deps)) return;
787
+ registerGitHubTools(api, integration, deps.externalWrites);
788
+ return createGitHubProvider(deps, integration, options);
789
+ }
790
+ export {
791
+ GITHUB_CHECKS_KIND,
792
+ GITHUB_ISSUE_CANCELLED_KIND,
793
+ GITHUB_PR_FEEDBACK_KIND,
794
+ GITHUB_PR_STATE_KIND,
795
+ GITHUB_PR_TERMINAL_KIND,
796
+ GITHUB_RELEASE_KIND,
797
+ GitHubClient,
798
+ assertGitHubRepository,
799
+ index_default as default,
800
+ describeGitHubEvent,
801
+ githubExternal,
802
+ githubIntegration,
803
+ githubIssueWatcherSource,
804
+ manifest,
805
+ parseGitHubProfiles,
806
+ resolveGitHubProjectBinding,
807
+ setupGitHubIntegration
808
+ };
809
+ //# sourceMappingURL=index.js.map