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