@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
@@ -0,0 +1,216 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import type { CoreServerSetupDeps } from "@leitwerk-dev/process-sdk";
3
+ import { conflictEvidence, createConflictReporter } from "@leitwerk-dev/repository-rebase";
4
+ import { createPollSchedule, emptyPollResult } from "@leitwerk-dev/watcher-utils";
5
+ import type { GitHubIntegration } from "./capability.js";
6
+ import {
7
+ describeGitHubEvent,
8
+ GITHUB_PR_STATE_KIND,
9
+ GITHUB_RELEASE_KIND,
10
+ type GitHubPullRequestSourceConfig,
11
+ } from "./external.js";
12
+ import { createGitHubIssuePolling } from "./issue-provider.js";
13
+ import { githubPollReporter } from "./poll-report.js";
14
+
15
+ function parse(value: unknown): GitHubPullRequestSourceConfig | null {
16
+ const config = asUnknownRecord(value) ?? {};
17
+ if (
18
+ ["profile", "owner", "repo", "headSha"].some(
19
+ (key) => typeof config[key] !== "string" || !(config[key] as string).trim(),
20
+ ) ||
21
+ typeof config.prNumber !== "number"
22
+ )
23
+ return null;
24
+ return {
25
+ profile: config.profile as string,
26
+ owner: config.owner as string,
27
+ repo: config.repo as string,
28
+ prNumber: config.prNumber,
29
+ headSha: config.headSha as string,
30
+ lastConflictKey: typeof config.lastConflictKey === "string" ? config.lastConflictKey : null,
31
+ feedbackCursor: typeof config.feedbackCursor === "number" ? config.feedbackCursor : 0,
32
+ pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s",
33
+ disabled: config.disabled === true,
34
+ eventKinds: Array.isArray(config.eventKinds)
35
+ ? config.eventKinds.filter(
36
+ (value): value is "checks" | "feedback" | "merged" | "closed" | "merge_conflict" =>
37
+ ["checks", "feedback", "merged", "closed", "merge_conflict"].includes(String(value)),
38
+ )
39
+ : undefined,
40
+ checkStatuses: Array.isArray(config.checkStatuses)
41
+ ? config.checkStatuses.filter((value): value is "pending" | "success" | "failure" =>
42
+ ["pending", "success", "failure"].includes(String(value)),
43
+ )
44
+ : undefined,
45
+ };
46
+ }
47
+
48
+ export function createGitHubProvider(
49
+ deps: CoreServerSetupDeps,
50
+ integration: GitHubIntegration,
51
+ options: { now?: () => number } = {},
52
+ ) {
53
+ const due = createPollSchedule();
54
+ const pollIssues = createGitHubIssuePolling(deps, integration, options);
55
+ const reportConflict = createConflictReporter(deps.externalSources, GITHUB_PR_STATE_KIND);
56
+ return deps.polling.create({
57
+ id: "github",
58
+ pollInterval: () => "5s",
59
+ isEnabled: () => true,
60
+ defaultIntervalMs: 5_000,
61
+ async pollOnce() {
62
+ const result = emptyPollResult();
63
+ const report = githubPollReporter(deps.externalSources, result);
64
+ await pollIssues(result);
65
+ await report.poll(GITHUB_PR_STATE_KIND, async (armed) => {
66
+ const config = parse(armed.resolved);
67
+ if (!config) {
68
+ result.errors.push(`${armed.id}:invalid_config`);
69
+ return;
70
+ }
71
+ if (config.disabled) return;
72
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
73
+ const now = options.now?.() ?? Date.now();
74
+ if (!due(key, config.pollInterval, now)) return;
75
+ try {
76
+ const client = integration.client(config.profile);
77
+ const pr = await client.getPullRequest(config.owner, config.repo, config.prNumber);
78
+ if (!config.eventKinds || config.eventKinds.includes("merge_conflict")) {
79
+ const conflict = conflictEvidence(config, pr, "github");
80
+ // GitHub's PR base SHA can lag the branch even while its state is behind.
81
+ if (conflict?.reason === "behind") {
82
+ const branch = await client.getCommit(config.owner, config.repo, conflict.baseBranch);
83
+ conflict.baseSha = branch.sha;
84
+ }
85
+ if (
86
+ await reportConflict(report, armed, conflict, config.lastConflictKey, {
87
+ summary: `PR #${pr.number} mergeability: ${pr.mergeable == null ? "unresolved" : (pr.mergeable_state ?? String(pr.mergeable))}`,
88
+ observedAt: new Date(now).toISOString(),
89
+ subject: `${config.owner}/${config.repo}#${pr.number}`,
90
+ revision: `${pr.head.sha}:${conflict?.baseSha ?? pr.base.sha}`,
91
+ })
92
+ )
93
+ return;
94
+ if (config.eventKinds?.length === 1) return;
95
+ }
96
+ let event: Record<string, unknown> | null = null;
97
+ let mergeKey = "";
98
+ if (pr.merged || pr.state === "closed") {
99
+ event = {
100
+ kind: pr.merged ? "merged" : "closed",
101
+ pullRequest: pr,
102
+ };
103
+ mergeKey = `terminal:${pr.number}:${pr.merged}`;
104
+ } else {
105
+ if (pr.head.sha !== config.headSha) return;
106
+ const readsFeedback = !config.eventKinds || config.eventKinds.includes("feedback");
107
+ const readsChecks = !config.eventKinds || config.eventKinds.includes("checks");
108
+ const [feedback, checks] = await Promise.all([
109
+ readsFeedback
110
+ ? client.listActionablePullRequestFeedback(
111
+ config.owner,
112
+ config.repo,
113
+ config.prNumber,
114
+ )
115
+ : Promise.resolve([]),
116
+ readsChecks || (deps.externalSources.observe && armed.generation)
117
+ ? client
118
+ .getCheckSummary(config.owner, config.repo, config.headSha)
119
+ .catch(async (error) => {
120
+ await report.observe(armed, {
121
+ refreshError:
122
+ error instanceof Error ? error.message : "Checks refresh failed",
123
+ });
124
+ if (readsChecks) throw error;
125
+ return null;
126
+ })
127
+ : Promise.resolve(null),
128
+ ]);
129
+ if (checks && checks.headSha !== config.headSha) return;
130
+ const refreshed = await client.getPullRequest(
131
+ config.owner,
132
+ config.repo,
133
+ config.prNumber,
134
+ );
135
+ if (
136
+ refreshed.state !== "open" ||
137
+ refreshed.merged ||
138
+ refreshed.head.sha !== config.headSha
139
+ )
140
+ return;
141
+ if (checks && deps.externalSources.observe && armed.generation) {
142
+ const description = describeGitHubEvent({ kind: "checks", checks });
143
+ await report.observe(armed, {
144
+ observation: {
145
+ ...description,
146
+ observedAt: new Date(now).toISOString(),
147
+ subject: `${config.owner}/${config.repo}#${config.prNumber}`,
148
+ revision: checks.headSha,
149
+ },
150
+ });
151
+ }
152
+ const unseen = feedback.filter(
153
+ (item) => item.id > config.feedbackCursor && item.author !== client.profile.botLogin,
154
+ );
155
+ if (unseen.length) {
156
+ const feedbackCursor = Math.max(...unseen.map((item) => item.id));
157
+ event = { kind: "feedback", feedback, feedbackCursor };
158
+ mergeKey = `feedback:${feedbackCursor}`;
159
+ } else if (readsChecks && checks && checks.status !== "pending") {
160
+ event = { kind: "checks", checks };
161
+ mergeKey = `checks:${checks.headSha}:${checks.status}`;
162
+ }
163
+ }
164
+ if (
165
+ !event ||
166
+ (config.eventKinds &&
167
+ !config.eventKinds.includes(
168
+ String(event.kind) as (typeof config.eventKinds)[number],
169
+ )) ||
170
+ (event.kind === "checks" &&
171
+ config.checkStatuses &&
172
+ !config.checkStatuses.includes(
173
+ (event.checks as { status: "pending" | "success" | "failure" }).status,
174
+ ))
175
+ )
176
+ return;
177
+ await report.fire(armed, event, mergeKey);
178
+ } catch (error) {
179
+ await report.observe(armed, {
180
+ refreshError: error instanceof Error ? error.message : "PR refresh failed",
181
+ });
182
+ throw error;
183
+ }
184
+ });
185
+ await report.poll(GITHUB_RELEASE_KIND, async (armed) => {
186
+ const config = asUnknownRecord(armed.resolved) ?? {};
187
+ if (
188
+ typeof config.profile !== "string" ||
189
+ typeof config.owner !== "string" ||
190
+ typeof config.repo !== "string" ||
191
+ typeof config.mergeSha !== "string"
192
+ )
193
+ return;
194
+ if (config.disabled === true) return;
195
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
196
+ const now = options.now?.() ?? Date.now();
197
+ if (!due(key, typeof config.pollInterval === "string" ? config.pollInterval : "30s", now))
198
+ return;
199
+ const client = integration.client(config.profile);
200
+ for (const release of await client.listReleases(config.owner, config.repo)) {
201
+ if (release.draft || release.prerelease) continue;
202
+ const commit = await client.getCommit(config.owner, config.repo, release.tag_name);
203
+ if (!(await client.isAncestor(config.owner, config.repo, config.mergeSha, commit.sha)))
204
+ continue;
205
+ await report.fire(
206
+ armed,
207
+ { release, commitSha: commit.sha },
208
+ `${release.id}:${commit.sha}`,
209
+ );
210
+ break;
211
+ }
212
+ });
213
+ return result;
214
+ },
215
+ });
216
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,384 @@
1
+ import { LocalForgeStore, type LocalRepositorySeed } from "@leitwerk-dev/test-support/local-git";
2
+ import { actionableFeedback, authorizedTrigger } from "./authorization.js";
3
+ import type { GitHubClientLike } from "./capability.js";
4
+ import type {
5
+ GitHubCheckSummary,
6
+ GitHubFeedbackItem,
7
+ GitHubIssue,
8
+ GitHubLabelEvent,
9
+ GitHubProfile,
10
+ GitHubPullRequest,
11
+ GitHubRelease,
12
+ } from "./client.js";
13
+ import { assertGitHubRepository } from "./client.js";
14
+
15
+ export interface LocalGitHubRepository {
16
+ repository: ReturnType<LocalGitHubAdapter["newRepository"]>;
17
+ issues: GitHubIssue[];
18
+ pulls: GitHubPullRequest[];
19
+ comments: Record<string, Array<ReturnType<LocalGitHubAdapter["newComment"]>>>;
20
+ feedback: Record<string, GitHubFeedbackItem[]>;
21
+ checks: Record<string, GitHubCheckSummary>;
22
+ releases: GitHubRelease[];
23
+ assets: Record<string, string>;
24
+ labels: Array<{ id: number; name: string }>;
25
+ labelEvents: Record<string, GitHubLabelEvent[]>;
26
+ reactions: Record<string, Array<{ id: number; content: string; user: { login: string } }>>;
27
+ feedbackEditors: Record<string, string | null>;
28
+ }
29
+ export interface LocalGitHubState {
30
+ version: 1;
31
+ sequence: number;
32
+ repositories: LocalGitHubRepository[];
33
+ failAfterPullRequestWrite: boolean;
34
+ members: string[];
35
+ failAfterWrite: string | null;
36
+ }
37
+ export interface LocalGitHubOptions {
38
+ root: string;
39
+ baseUrl: string;
40
+ now?: () => number;
41
+ nextId?: () => number;
42
+ seeds?: LocalRepositorySeed[];
43
+ allowedOrganization?: string;
44
+ }
45
+
46
+ /** Persistent local GitHub with actual commit ancestry and configurable release assets. */
47
+ export class LocalGitHubAdapter extends LocalForgeStore<LocalGitHubState, LocalGitHubOptions> {
48
+ constructor(options: LocalGitHubOptions) {
49
+ super(options, "github.json", {
50
+ version: 1,
51
+ sequence: 0,
52
+ repositories: [],
53
+ failAfterPullRequestWrite: false,
54
+ members: [],
55
+ failAfterWrite: null,
56
+ });
57
+ this.state.members ??= [];
58
+ this.state.failAfterWrite ??= null;
59
+ for (const r of this.state.repositories) {
60
+ r.labels ??= [];
61
+ r.labelEvents ??= {};
62
+ r.reactions ??= {};
63
+ r.feedbackEditors ??= {};
64
+ }
65
+ for (const seed of options.seeds ?? []) this.seed(seed);
66
+ }
67
+ repo(owner: string, name: string) {
68
+ const repo = this.state.repositories.find((r) => r.repository.full_name === `${owner}/${name}`);
69
+ if (!repo) throw new Error("Unknown local GitHub repository");
70
+ return repo;
71
+ }
72
+ seed(seed: LocalRepositorySeed) {
73
+ const existing = this.state.repositories.find(
74
+ (r) => r.repository.full_name === `${seed.owner}/${seed.name}`,
75
+ );
76
+ if (existing) return existing;
77
+ const repo: LocalGitHubRepository = {
78
+ repository: this.newRepository(seed),
79
+ issues: [],
80
+ pulls: [],
81
+ comments: {},
82
+ feedback: {},
83
+ checks: {},
84
+ releases: [],
85
+ assets: {},
86
+ labels: [],
87
+ labelEvents: {},
88
+ reactions: {},
89
+ feedbackEditors: {},
90
+ };
91
+ this.state.repositories.push(repo);
92
+ this.save();
93
+ return repo;
94
+ }
95
+ setChecks(repo: LocalGitHubRepository, summary: GitHubCheckSummary) {
96
+ this.git.head(repo.repository.ssh_url, summary.headSha);
97
+ repo.checks[summary.headSha] = structuredClone(summary);
98
+ this.save();
99
+ }
100
+ publishRelease(
101
+ repo: LocalGitHubRepository,
102
+ input: {
103
+ tag: string;
104
+ ref: string;
105
+ assets: Record<string, string>;
106
+ draft?: boolean;
107
+ prerelease?: boolean;
108
+ },
109
+ ) {
110
+ const commit = this.git.head(repo.repository.ssh_url, input.ref);
111
+ this.git.run(repo.repository.ssh_url, ["check-ref-format", `refs/tags/${input.tag}`]);
112
+ this.git.run(repo.repository.ssh_url, ["tag", "--", input.tag, commit]);
113
+ const id = this.id();
114
+ const release: GitHubRelease = {
115
+ id,
116
+ tag_name: input.tag,
117
+ target_commitish: commit,
118
+ draft: input.draft ?? false,
119
+ prerelease: input.prerelease ?? false,
120
+ html_url: `${this.options.baseUrl}/__local`,
121
+ assets: Object.entries(input.assets).map(([name, contents]) => {
122
+ const url = `${this.options.baseUrl}/__local/assets/${this.id()}`;
123
+ repo.assets[url] = contents;
124
+ return { name, url, browser_download_url: url };
125
+ }),
126
+ };
127
+ repo.releases.unshift(release);
128
+ this.save();
129
+ return release;
130
+ }
131
+ override newRepository(seed: LocalRepositorySeed) {
132
+ return { ...super.newRepository(seed), archived: false, has_issues: true };
133
+ }
134
+ setMembership(login: string, member: boolean) {
135
+ this.state.members = this.state.members.filter(
136
+ (value) => value.toLowerCase() !== login.toLowerCase(),
137
+ );
138
+ if (member) this.state.members.push(login);
139
+ this.save();
140
+ }
141
+ failNextResponse(operation: "comment" | "reply" | "reaction" | "issue" | "label") {
142
+ this.state.failAfterWrite = operation;
143
+ this.save();
144
+ }
145
+ private lostResponse(operation: string) {
146
+ if (this.state.failAfterWrite !== operation) return;
147
+ this.state.failAfterWrite = null;
148
+ this.save();
149
+ throw new Error(`Local GitHub: response lost after ${operation} write`);
150
+ }
151
+ createIssue(
152
+ repo: LocalGitHubRepository,
153
+ input: { title: string; body?: string; author?: string },
154
+ ) {
155
+ const number = this.id();
156
+ const issue: GitHubIssue = {
157
+ number,
158
+ title: input.title,
159
+ body: input.body ?? "",
160
+ state: "open",
161
+ html_url: `${this.options.baseUrl}/__local#issue-${number}`,
162
+ updated_at: this.timestamp(),
163
+ user: { login: input.author ?? "developer" },
164
+ labels: [],
165
+ };
166
+ repo.issues.push(issue);
167
+ this.save();
168
+ return issue;
169
+ }
170
+ setIssueLabel(
171
+ repo: LocalGitHubRepository,
172
+ number: number,
173
+ name: string,
174
+ actor: string,
175
+ present = true,
176
+ ) {
177
+ const issue = repo.issues.find((value) => value.number === number);
178
+ if (!issue) throw new Error("Unknown local GitHub issue");
179
+ issue.labels = issue.labels.filter((label) => label.name !== name);
180
+ if (present) issue.labels.push({ id: this.id(), name });
181
+ const event: GitHubLabelEvent = {
182
+ id: this.id(),
183
+ event: present ? "labeled" : "unlabeled",
184
+ label: { name },
185
+ actor: { login: actor },
186
+ };
187
+ repo.labelEvents[number] ??= [];
188
+ repo.labelEvents[number].push(event);
189
+ issue.updated_at = this.timestamp();
190
+ this.save();
191
+ return event;
192
+ }
193
+ editFeedback(
194
+ repo: LocalGitHubRepository,
195
+ number: number,
196
+ kind: GitHubFeedbackItem["kind"],
197
+ id: number,
198
+ body: string,
199
+ editor: string | null,
200
+ ) {
201
+ const item = repo.feedback[number]?.find((value) => value.kind === kind && value.id === id);
202
+ if (!item) throw new Error("Unknown local GitHub feedback");
203
+ item.body = body;
204
+ item.createdAt = this.timestamp();
205
+ repo.feedbackEditors[`${kind}:${id}`] = editor;
206
+ this.save();
207
+ }
208
+
209
+ client(): GitHubClientLike {
210
+ const profile: GitHubProfile = {
211
+ apiBaseUrl: this.options.baseUrl,
212
+ token: "",
213
+ botLogin: "leitwerk-bot",
214
+ ...(this.options.allowedOrganization
215
+ ? { allowedOrganization: this.options.allowedOrganization }
216
+ : {}),
217
+ };
218
+ const repo = (owner: string, name: string) => {
219
+ assertGitHubRepository(profile, owner, name);
220
+ return this.repo(owner, name);
221
+ };
222
+ const client: GitHubClientLike = {
223
+ profile,
224
+ listRepositories: async () =>
225
+ this.state.repositories
226
+ .map((r) => ({ ...r.repository, archived: false, has_issues: true }))
227
+ .filter(
228
+ (r) =>
229
+ !profile.allowedOrganization ||
230
+ r.owner.login.toLowerCase() === profile.allowedOrganization.toLowerCase(),
231
+ ),
232
+ listOpenIssues: async (owner, name) =>
233
+ structuredClone(repo(owner, name).issues.filter((i) => i.state === "open")),
234
+ listIssueEvents: async (owner, name, number) =>
235
+ structuredClone(repo(owner, name).labelEvents[number] ?? []),
236
+ isOrganizationMember: async (login) =>
237
+ !profile.allowedOrganization ||
238
+ this.state.members.some((member) => member.toLowerCase() === login.toLowerCase()),
239
+ authorizedTrigger: async (owner, name, number, trigger, done) =>
240
+ authorizedTrigger(client, owner, name, number, trigger, done),
241
+ resolveGitIdentity: async (name) => ({
242
+ provider: "github",
243
+ profile: name,
244
+ login: profile.botLogin,
245
+ name: "Sandbox Developer",
246
+ email: "developer@sandbox.invalid",
247
+ }),
248
+ ensureLabel: async (owner, name, labelName) => {
249
+ const r = repo(owner, name);
250
+ let label = r.labels.find((value) => value.name === labelName);
251
+ if (!label) {
252
+ label = { id: this.id(), name: labelName };
253
+ r.labels.push(label);
254
+ this.save();
255
+ this.lostResponse("label");
256
+ }
257
+ return structuredClone(label);
258
+ },
259
+ updateIssue: async (owner, name, number, patch) => {
260
+ const issue = repo(owner, name).issues.find((i) => i.number === number);
261
+ if (!issue) throw new Error("Unknown local GitHub issue");
262
+ for (const key of ["title", "body", "state"] as const)
263
+ if (typeof patch[key] === "string") issue[key] = patch[key];
264
+ if (Array.isArray(patch.labels))
265
+ issue.labels = patch.labels.map((value) => ({ id: this.id(), name: String(value) }));
266
+ issue.updated_at = this.timestamp();
267
+ this.save();
268
+ this.lostResponse("issue");
269
+ return structuredClone(issue);
270
+ },
271
+ listFeedbackReactions: async (owner, name, kind, id) =>
272
+ structuredClone(repo(owner, name).reactions[`${kind}:${id}`] ?? []),
273
+ addFeedbackReaction: async (owner, name, kind, id) => {
274
+ if (!["conversation", "inline"].includes(kind))
275
+ throw new Error("Reviews do not support reactions");
276
+ const r = repo(owner, name);
277
+ r.reactions[`${kind}:${id}`] ??= [];
278
+ const reactions = r.reactions[`${kind}:${id}`];
279
+ let reaction = reactions.find(
280
+ (r) => r.content === "eyes" && r.user.login === profile.botLogin,
281
+ );
282
+ if (!reaction) {
283
+ reaction = { id: this.id(), content: "eyes", user: { login: profile.botLogin } };
284
+ reactions.push(reaction);
285
+ this.save();
286
+ this.lostResponse("reaction");
287
+ }
288
+ return structuredClone(reaction);
289
+ },
290
+ listFeedbackReplies: async (owner, name, number, kind) =>
291
+ kind === "inline"
292
+ ? structuredClone(
293
+ (repo(owner, name).feedback[number] ?? [])
294
+ .filter((f) => f.kind === "inline")
295
+ .map((f) => ({ ...f })),
296
+ )
297
+ : client.listIssueComments(owner, name, number),
298
+ replyFeedback: async (owner, name, number, kind, _id, body) => {
299
+ if (kind !== "inline") return client.addIssueComment(owner, name, number, body);
300
+ const value = this.addFeedback(repo(owner, name), number, {
301
+ kind: "inline",
302
+ body,
303
+ author: profile.botLogin,
304
+ });
305
+ this.lostResponse("reply");
306
+ return structuredClone(value);
307
+ },
308
+ listActionablePullRequestFeedback: async (owner, name, number, signal) =>
309
+ actionableFeedback(
310
+ client,
311
+ await client.listPullRequestFeedback(owner, name, number, signal),
312
+ ),
313
+ getIssue: async (owner, name, number) => {
314
+ const issue = repo(owner, name).issues.find((i) => i.number === number);
315
+ if (!issue) throw new Error("Unknown local GitHub issue");
316
+ return structuredClone(issue);
317
+ },
318
+ getCommit: async (owner, name, ref) => ({
319
+ sha: this.git.head(repo(owner, name).repository.ssh_url, ref),
320
+ }),
321
+ isAncestor: async (owner, name, ancestor, descendant) =>
322
+ this.git.isAncestor(repo(owner, name).repository.ssh_url, ancestor, descendant),
323
+ listIssueComments: async (owner, name, number) =>
324
+ structuredClone(repo(owner, name).comments[number] ?? []),
325
+ addIssueComment: async (owner, name, number, body) => {
326
+ const r = repo(owner, name);
327
+ if (!r.pulls.some((p) => p.number === number) && !r.issues.some((i) => i.number === number))
328
+ throw new Error("Unknown local GitHub issue or PR");
329
+ const value = this.newComment(body);
330
+ r.comments[number] ??= [];
331
+ r.comments[number].push(value);
332
+ this.save();
333
+ this.lostResponse("comment");
334
+ return structuredClone(value);
335
+ },
336
+ createPullRequest: async (owner, name, input) => {
337
+ const r = repo(owner, name);
338
+ const pr = this.newPullRequest(r, input);
339
+ r.pulls.push(pr);
340
+ const fail = this.state.failAfterPullRequestWrite;
341
+ this.state.failAfterPullRequestWrite = false;
342
+ this.save();
343
+ if (fail) throw new Error("Local GitHub: response lost after PR creation");
344
+ return this.refresh(r, pr);
345
+ },
346
+ ...this.pullRequestClient(repo, "Unknown local GitHub pull request"),
347
+ listPullRequestFeedback: async (owner, name, number) =>
348
+ structuredClone([
349
+ ...(repo(owner, name).feedback[number] ?? []).filter((item) => {
350
+ if (!profile.allowedOrganization) return true;
351
+ const editor = repo(owner, name).feedbackEditors[`${item.kind}:${item.id}`];
352
+ return (
353
+ editor === undefined ||
354
+ (editor !== null &&
355
+ this.state.members.some((m) => m.toLowerCase() === editor.toLowerCase()))
356
+ );
357
+ }),
358
+ ...(repo(owner, name).comments[number] ?? []).map((c) => ({
359
+ kind: "conversation" as const,
360
+ id: c.id,
361
+ body: c.body,
362
+ author: c.user.login,
363
+ createdAt: c.created_at,
364
+ })),
365
+ ]),
366
+ getCheckSummary: async (owner, name, sha) =>
367
+ structuredClone(
368
+ repo(owner, name).checks[sha] ?? {
369
+ headSha: sha,
370
+ status: "pending",
371
+ total: 0,
372
+ failed: [],
373
+ },
374
+ ),
375
+ listReleases: async (owner, name) => structuredClone(repo(owner, name).releases),
376
+ downloadReleaseAsset: async (asset) => {
377
+ for (const r of this.state.repositories)
378
+ if (r.assets[asset.url] !== undefined) return r.assets[asset.url];
379
+ throw new Error("Unknown local GitHub release asset");
380
+ },
381
+ };
382
+ return client;
383
+ }
384
+ }