@kana-ai/edgar-ext-github 0.0.0-stage → 0.1.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 (136) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +469 -2
  3. package/agents/dismiss/agent.toml +4 -0
  4. package/agents/dismiss/instructions.md +25 -0
  5. package/dist/src/api/app.d.ts +16 -0
  6. package/dist/src/api/app.js +32 -0
  7. package/dist/src/api/client.d.ts +26 -0
  8. package/dist/src/api/client.js +103 -0
  9. package/dist/src/api/failures.d.ts +8 -0
  10. package/dist/src/api/failures.js +31 -0
  11. package/dist/src/feed/alerts.d.ts +26 -0
  12. package/dist/src/feed/alerts.js +117 -0
  13. package/dist/src/feed/cards.d.ts +32 -0
  14. package/dist/src/feed/cards.js +164 -0
  15. package/dist/src/feed/service.d.ts +28 -0
  16. package/dist/src/feed/service.js +163 -0
  17. package/dist/src/index.d.ts +490 -0
  18. package/dist/src/index.js +62 -0
  19. package/dist/src/schemas/config.d.ts +57 -0
  20. package/dist/src/schemas/config.js +89 -0
  21. package/dist/src/schemas/github.d.ts +417 -0
  22. package/dist/src/schemas/github.js +216 -0
  23. package/dist/src/schemas/tools.d.ts +620 -0
  24. package/dist/src/schemas/tools.js +501 -0
  25. package/dist/src/tools/alerts.d.ts +45 -0
  26. package/dist/src/tools/alerts.js +100 -0
  27. package/dist/src/tools/branch.d.ts +9 -0
  28. package/dist/src/tools/branch.js +48 -0
  29. package/dist/src/tools/checks.d.ts +118 -0
  30. package/dist/src/tools/checks.js +223 -0
  31. package/dist/src/tools/discussion.d.ts +41 -0
  32. package/dist/src/tools/discussion.js +66 -0
  33. package/dist/src/tools/pull-request.d.ts +195 -0
  34. package/dist/src/tools/pull-request.js +537 -0
  35. package/dist/src/tools/repository.d.ts +53 -0
  36. package/dist/src/tools/repository.js +134 -0
  37. package/dist/src/tools/screenshot.d.ts +21 -0
  38. package/dist/src/tools/screenshot.js +99 -0
  39. package/dist/src/tracker/assignee.d.ts +15 -0
  40. package/dist/src/tracker/assignee.js +65 -0
  41. package/dist/src/tracker/cards.d.ts +41 -0
  42. package/dist/src/tracker/cards.js +361 -0
  43. package/dist/src/tracker/comments.d.ts +9 -0
  44. package/dist/src/tracker/comments.js +68 -0
  45. package/dist/src/tracker/description.d.ts +19 -0
  46. package/dist/src/tracker/description.js +55 -0
  47. package/dist/src/tracker/hand-back.d.ts +8 -0
  48. package/dist/src/tracker/hand-back.js +60 -0
  49. package/dist/src/tracker/port.d.ts +2 -0
  50. package/dist/src/tracker/port.js +42 -0
  51. package/dist/src/tracker/states.d.ts +77 -0
  52. package/dist/src/tracker/states.js +189 -0
  53. package/dist/src/tracker/tools.d.ts +143 -0
  54. package/dist/src/tracker/tools.js +131 -0
  55. package/dist/src/tracker/transitions.d.ts +12 -0
  56. package/dist/src/tracker/transitions.js +101 -0
  57. package/edgar-extension.json +507 -0
  58. package/package.json +43 -3
  59. package/schemas/assign.in.json +15 -0
  60. package/schemas/assign.out.json +14 -0
  61. package/schemas/attach_screenshot.in.json +44 -0
  62. package/schemas/attach_screenshot.out.json +31 -0
  63. package/schemas/batch_cards.in.json +27 -0
  64. package/schemas/batch_cards.out.json +37 -0
  65. package/schemas/branch_protection.in.json +15 -0
  66. package/schemas/branch_protection.out.json +67 -0
  67. package/schemas/ci_run.in.json +12 -0
  68. package/schemas/ci_run.out.json +109 -0
  69. package/schemas/close.in.json +14 -0
  70. package/schemas/close.out.json +10 -0
  71. package/schemas/close_pull_request.in.json +21 -0
  72. package/schemas/close_pull_request.out.json +14 -0
  73. package/schemas/comment.in.json +19 -0
  74. package/schemas/comment.out.json +10 -0
  75. package/schemas/config.json +202 -0
  76. package/schemas/count_sighting.in.json +17 -0
  77. package/schemas/count_sighting.out.json +10 -0
  78. package/schemas/create_card.in.json +108 -0
  79. package/schemas/create_card.out.json +13 -0
  80. package/schemas/dependabot_alerts.in.json +49 -0
  81. package/schemas/dependabot_alerts.out.json +75 -0
  82. package/schemas/dismiss_dependabot_alert.in.json +26 -0
  83. package/schemas/dismiss_dependabot_alert.out.json +27 -0
  84. package/schemas/find_assignee.in.json +15 -0
  85. package/schemas/find_assignee.out.json +10 -0
  86. package/schemas/find_cards.in.json +18 -0
  87. package/schemas/find_cards.out.json +33 -0
  88. package/schemas/find_dependabot_dismissal.in.json +12 -0
  89. package/schemas/find_dependabot_dismissal.out.json +27 -0
  90. package/schemas/find_description.in.json +15 -0
  91. package/schemas/find_description.out.json +10 -0
  92. package/schemas/find_pull_request.in.json +25 -0
  93. package/schemas/find_pull_request.out.json +14 -0
  94. package/schemas/hand_back.in.json +11 -0
  95. package/schemas/hand_back.out.json +18 -0
  96. package/schemas/linked_pull_requests.in.json +15 -0
  97. package/schemas/linked_pull_requests.out.json +44 -0
  98. package/schemas/list_pull_requests.in.json +26 -0
  99. package/schemas/list_pull_requests.out.json +42 -0
  100. package/schemas/merge_pull_request.in.json +22 -0
  101. package/schemas/merge_pull_request.out.json +16 -0
  102. package/schemas/move.in.json +15 -0
  103. package/schemas/move.out.json +10 -0
  104. package/schemas/note_pull_request.in.json +15 -0
  105. package/schemas/note_pull_request.out.json +10 -0
  106. package/schemas/open_pull_request.in.json +113 -0
  107. package/schemas/open_pull_request.out.json +15 -0
  108. package/schemas/pull_request_checks.in.json +11 -0
  109. package/schemas/pull_request_checks.out.json +72 -0
  110. package/schemas/pull_request_discussion.in.json +11 -0
  111. package/schemas/pull_request_discussion.out.json +107 -0
  112. package/schemas/pull_request_state.in.json +11 -0
  113. package/schemas/pull_request_state.out.json +52 -0
  114. package/schemas/push_branch.in.json +21 -0
  115. package/schemas/push_branch.out.json +13 -0
  116. package/schemas/release_follow_ups.in.json +15 -0
  117. package/schemas/release_follow_ups.out.json +13 -0
  118. package/schemas/reopen_dependabot_alert.in.json +33 -0
  119. package/schemas/reopen_dependabot_alert.out.json +22 -0
  120. package/schemas/restore_assignee.in.json +20 -0
  121. package/schemas/restore_assignee.out.json +10 -0
  122. package/schemas/restore_description.in.json +20 -0
  123. package/schemas/restore_description.out.json +10 -0
  124. package/schemas/update_description.in.json +15 -0
  125. package/schemas/update_description.out.json +14 -0
  126. package/schemas/update_pull_request.in.json +81 -0
  127. package/schemas/update_pull_request.out.json +10 -0
  128. package/schemas/wait_for_checks.in.json +11 -0
  129. package/schemas/wait_for_checks.out.json +72 -0
  130. package/schemas/wait_for_merge.in.json +11 -0
  131. package/schemas/wait_for_merge.out.json +17 -0
  132. package/schemas/wait_for_passed_checks.in.json +11 -0
  133. package/schemas/wait_for_passed_checks.out.json +72 -0
  134. package/schemas/wait_for_review.in.json +11 -0
  135. package/schemas/wait_for_review.out.json +52 -0
  136. package/workflows/resume.toml +17 -0
@@ -0,0 +1,537 @@
1
+ import { defineTool, disableTool, done, err, ok, permanentFailure, skipped, } from "@kana-ai/edgar-sdk";
2
+ import { z } from "zod";
3
+ import { apiAccess, github } from "#api/client";
4
+ import { config } from "#schemas/config";
5
+ import { comparison, linkedPull, merge, note, pull, pullBody, pullFile, review, } from "#schemas/github";
6
+ import { attachScreenshot, closePullRequest, findPullRequest, linkedPullRequests, listPullRequests, mergePullRequest, notePullRequest, openPullRequest, pullRequestState, updatePullRequest, waitForMerge, } from "#schemas/tools";
7
+ import { picture, said, screenshotOf, withScreenshot } from "#tools/screenshot";
8
+ function stateOf(value) {
9
+ return value.merged_at === null ? value.state : "merged";
10
+ }
11
+ /** `owner/name` in lower case from `owner/name`, an SSH remote or an HTTPS URL of github.com: GitHub names are not case-sensitive, so one repository has one name in every key. */
12
+ export function repoPath(repo) {
13
+ const [, owner, name] = /^(?:git@github\.com:|https:\/\/github\.com\/)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(repo) ?? [];
14
+ return owner === undefined || name === undefined ? undefined : `${owner}/${name}`.toLowerCase();
15
+ }
16
+ /** The API path of a pull request from its `https://github.com/<owner>/<name>/pull/<n>` URL. */
17
+ export function pullPath(url) {
18
+ const [, repo, number] = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/.exec(url) ?? [];
19
+ return repo === undefined || number === undefined ? undefined : `/repos/${repo}/pulls/${number}`;
20
+ }
21
+ /** The card id of an `edgar/<card>-<slug>` branch, as `ENG-123`, or `null`. */
22
+ export function cardOf(branch) {
23
+ return /^edgar\/([A-Za-z][A-Za-z0-9]*-\d+)(?:-|$)/.exec(branch)?.[1] ?? null;
24
+ }
25
+ /** Each reviewer's latest deciding review: an approval or a change request. */
26
+ function decided(reviews) {
27
+ const latest = new Map();
28
+ for (const r of reviews) {
29
+ if (r.user === null || (r.state !== "APPROVED" && r.state !== "CHANGES_REQUESTED"))
30
+ continue;
31
+ const said = { login: r.user.login, state: r.state };
32
+ latest.set(r.user.id, typeof r.commit_id === "string" ? { ...said, commit: r.commit_id } : said);
33
+ }
34
+ return [...latest.values()];
35
+ }
36
+ /** The review state from each reviewer's latest deciding review. A change request made on a commit before `head` is pending: a push answered it, and its reviewer has not reviewed the new head, so no approval of another reviewer counts yet. */
37
+ export function reviewState(reviews, head) {
38
+ const latest = decided(reviews);
39
+ const asked = latest.filter(({ state }) => state === "CHANGES_REQUESTED");
40
+ const current = ({ commit }) => head === undefined || commit === undefined || commit === head;
41
+ if (asked.some(current))
42
+ return "changes_requested";
43
+ if (asked.length > 0)
44
+ return "pending";
45
+ return latest.some(({ state }) => state === "APPROVED") ? "approved" : "pending";
46
+ }
47
+ /** What `pull_request_state` answers: the pull request and its reviews in two reads. shortcut: the oldest 100 reviews only, so a later approval is not read; upgrade to `Link` pagination when a pull request holds more. */
48
+ async function stateOfPull(ctx, url) {
49
+ const path = pullOf(url);
50
+ if (!path.ok)
51
+ return path.error;
52
+ const read = await github(ctx, "GET", path.value, pull);
53
+ if (!read.ok)
54
+ return read.error;
55
+ const reviews = await github(ctx, "GET", `${path.value}/reviews?per_page=100`, z.array(review));
56
+ if (!reviews.ok)
57
+ return reviews.error;
58
+ const p = read.value;
59
+ const merged = p.merged_at !== null;
60
+ return done({
61
+ url: p.html_url,
62
+ state: stateOf(p),
63
+ merged,
64
+ review_state: reviewState(reviews.value, p.head.sha),
65
+ approved_by: decided(reviews.value)
66
+ .filter(({ state }) => state === "APPROVED")
67
+ .map(({ login }) => login),
68
+ card: cardOf(p.head.ref),
69
+ commit: merged ? (p.merge_commit_sha ?? p.head.sha) : p.head.sha,
70
+ branch: p.head.ref,
71
+ head_repo: p.head.repo?.full_name ?? null,
72
+ });
73
+ }
74
+ /** The pull requests that the `Goes with:` line of `body` names and that are not merged. One that answers 404 or 403 is `closed`, because no one can merge it through EDGAR. */
75
+ async function unmergedOf(ctx, body) {
76
+ const links = /^Goes with: (.+)$/m.exec(body ?? "")?.[1]?.split(",") ?? [];
77
+ const found = [];
78
+ for (const link of links.map((text) => text.trim())) {
79
+ const path = pullPath(link);
80
+ if (path === undefined)
81
+ continue;
82
+ const read = await github(ctx, "GET", path, pull);
83
+ if (!read.ok && (read.error.kind === "not_found" || read.error.kind === "forbidden")) {
84
+ found.push({ url: link, state: "closed" });
85
+ continue;
86
+ }
87
+ if (!read.ok)
88
+ return read;
89
+ if (read.value.merged_at === null)
90
+ found.push({ url: read.value.html_url, state: read.value.state });
91
+ }
92
+ return ok(found);
93
+ }
94
+ /** `owner/name` of a repository, or `invalid_input`. */
95
+ export function repoOf(repo) {
96
+ const path = repoPath(repo);
97
+ return path === undefined
98
+ ? err(permanentFailure("invalid_input", `${repo} is not a github.com repository`))
99
+ : ok(path);
100
+ }
101
+ /** The API path of a pull request URL, or `invalid_input`. */
102
+ export function pullOf(url) {
103
+ const path = pullPath(url);
104
+ return path === undefined
105
+ ? err(permanentFailure("invalid_input", `${url} is not a github.com pull request URL`))
106
+ : ok(path);
107
+ }
108
+ function headOf(repo, branch) {
109
+ const [owner] = repo.split("/");
110
+ return encodeURIComponent(`${owner ?? ""}:${branch}`);
111
+ }
112
+ /**
113
+ * The lines the body adds for the change's size and the paths it touches; with neither input, no call is made.
114
+ * A failed compare gives no lines and goes to the runtime log, because an optional warning never costs a finished fix its pull request.
115
+ */
116
+ async function noticesOf(ctx, repo, base, input) {
117
+ const paths = input.path_notices ?? [];
118
+ if (input.large_diff_lines === undefined && paths.length === 0)
119
+ return [];
120
+ const range = `${encodeURIComponent(base)}...${encodeURIComponent(input.branch)}`;
121
+ const compared = await github(ctx, "GET", `/repos/${repo}/compare/${range}`, comparison);
122
+ if (compared.ok)
123
+ return changeNotices(compared.value.files, input.large_diff_lines, paths);
124
+ ctx.log(`notices left out of the pull request of ${input.branch}: ${compared.error.message}`);
125
+ return [];
126
+ }
127
+ /** The large change line past `largeLines` changed lines, then each path notice whose prefix a file is under, once each. */
128
+ export function changeNotices(files, largeLines, paths) {
129
+ const lines = files.reduce((sum, f) => sum + f.changes, 0);
130
+ const plural = files.length === 1 ? "" : "s";
131
+ const large = largeLines !== undefined && lines > largeLines
132
+ ? [`**Large change.** ${String(lines)} lines across ${String(files.length)} file${plural}.`]
133
+ : [];
134
+ const touched = paths
135
+ .filter((p) => files.some((f) => f.filename.startsWith(p.prefix)))
136
+ .map((p) => p.notice);
137
+ return [...large, ...new Set(touched)];
138
+ }
139
+ function bodyOf(...parts) {
140
+ return parts.filter((part) => part !== "").join("\n\n");
141
+ }
142
+ /** The proof of a change as the body shows it. "Verified" lists each check that ended with exit code 0, from the check stage's own results and from no words of a model. "Not verified" lists each other check, then each thing the author did not check; a check with no exit code did not run, because a check before it failed, or did not end. With `checks`, "Verified" is there also when it is empty, so a reader can tell that nothing passed, or that nothing ran, from a body with no proof. "Not verified" says that nothing is outstanding only when the author gave a list and it is empty. With neither input, the body has no proof. */
143
+ export function proofOf(checks, notVerified) {
144
+ const results = checks?.results ?? [];
145
+ const name = (check) => `\`${check.replaceAll("`", "")}\``;
146
+ const passed = results.filter((r) => r.exit_code === 0).map((r) => `- ${name(r.check)} passed`);
147
+ const open = [
148
+ ...results
149
+ .filter((r) => r.exit_code !== 0)
150
+ .map((r) => r.exit_code === null
151
+ ? `- ${name(r.check)} did not run or did not end`
152
+ : `- ${name(r.check)} ended with exit code ${String(r.exit_code)}`),
153
+ ...(notVerified ?? [])
154
+ .map((item) => item.trim().replaceAll(/\s+/g, " "))
155
+ .filter((item) => item !== "")
156
+ .map((item) => `- ${item}`),
157
+ ];
158
+ const none = results.length === 0
159
+ ? "**Verified:** nothing was run. No check applies to this service."
160
+ : "**Verified:** nothing passed.";
161
+ const verified = checks === undefined
162
+ ? []
163
+ : [passed.length === 0 ? none : ["**Verified:**", ...passed].join("\n")];
164
+ const outstanding = notVerified === undefined ? [] : ["**Not verified:** nothing outstanding."];
165
+ return [
166
+ ...verified,
167
+ ...(open.length === 0 ? outstanding : [["**Not verified:**", ...open].join("\n")]),
168
+ ];
169
+ }
170
+ /** `done` with the pull request, after its labels are added; a refused label is logged and the pull request stays done, because the change is open and labels only sort it. */
171
+ async function labelled(ctx, repo, made, labels) {
172
+ if (labels !== undefined && labels.length > 0) {
173
+ const added = await github(ctx, "POST", `/repos/${repo}/issues/${String(made.number)}/labels`, z.array(z.object({ name: z.string() })), { labels });
174
+ if (!added.ok)
175
+ ctx.log(`labels not added to ${made.html_url}: ${added.error.message}`);
176
+ }
177
+ return done({ url: made.html_url, number: made.number });
178
+ }
179
+ /** The first line of EDGAR's note on a pull request, which GitHub does not show, and the title under it. */
180
+ const NOTE_MARK = "<!-- edgar:note -->";
181
+ const NOTE_TITLE = "**EDGAR's notes on this pull request**";
182
+ /** Adds `text` as one item of EDGAR's one note on the pull request at the API `path`: the comment that starts with the note's mark, made when there is none. The item keeps the lines of `text`, indented under its bullet, so its paragraphs and lists stay. An item that is already the last one writes nothing. */
183
+ async function noted(ctx, path, text) {
184
+ const comments = `${path.replace("/pulls/", "/issues/")}/comments`;
185
+ const [first = "", ...rest] = text
186
+ .trim()
187
+ .split(/\r?\n/)
188
+ .map((part) => part.trimEnd());
189
+ const line = [`- ${first}`, ...rest.map((part) => (part === "" ? "" : ` ${part}`))].join("\n");
190
+ const read = await github(ctx, "GET", `${comments}?per_page=100`, z.array(note));
191
+ if (!read.ok)
192
+ return read.error;
193
+ const kept = read.value.find((comment) => comment.body?.startsWith(NOTE_MARK) === true);
194
+ if (kept === undefined) {
195
+ const made = await github(ctx, "POST", comments, note, {
196
+ body: `${NOTE_MARK}\n${NOTE_TITLE}\n\n${line}`,
197
+ });
198
+ return made.ok ? done({ url: made.value.html_url }) : made.error;
199
+ }
200
+ const body = kept.body ?? "";
201
+ if (body.endsWith(`\n${line}`))
202
+ return done({ url: kept.html_url });
203
+ const repo = comments.slice(0, comments.indexOf("/issues/"));
204
+ const written = await github(ctx, "PATCH", `${repo}/issues/comments/${String(kept.id)}`, note, {
205
+ body: `${body}\n${line}`,
206
+ });
207
+ return written.ok ? done({ url: written.value.html_url }) : written.error;
208
+ }
209
+ /** The pull request tools of the GitHub extension, by the name the manifest gives them. */
210
+ export const pullRequestTools = {
211
+ /** A retry after a lost answer gets 422 for the pull request its earlier attempt opened: a 422 reads the branch's open pull request back and returns it, and stays `invalid` when there is none. */
212
+ open_pull_request: defineTool({
213
+ description: "Open a pull request from a pushed edgar/ branch onto the default base",
214
+ input: openPullRequest.input,
215
+ output: openPullRequest.output,
216
+ ...apiAccess,
217
+ side_effect: true,
218
+ compensate: "close_pull_request",
219
+ lookup: "find_pull_request",
220
+ execute: async (input, ctx) => {
221
+ const settings = config.safeParse(ctx.config ?? {});
222
+ if (!settings.success) {
223
+ return permanentFailure("invalid", "the [extensions.github] table does not match its schema");
224
+ }
225
+ const repo = repoOf(input.repo);
226
+ if (!repo.ok)
227
+ return repo.error;
228
+ const base = settings.data.default_base;
229
+ const notes = await noticesOf(ctx, repo.value, base, input);
230
+ const related = typeof input.related === "string" ? [input.related] : (input.related ?? []);
231
+ const body = bodyOf(input.body, related.length === 0 ? "" : `Goes with: ${related.join(", ")}`, ...notes, ...proofOf(input.checks, input.not_verified), input.review === ""
232
+ ? ""
233
+ : `Before I opened this, a second model reviewed the change. ${input.review}`, `edgar-operation: ${ctx.operation_id}`);
234
+ const made = await github(ctx, "POST", `/repos/${repo.value}/pulls`, pull, {
235
+ title: input.title,
236
+ head: input.branch,
237
+ base,
238
+ body,
239
+ });
240
+ if (made.ok)
241
+ return await labelled(ctx, repo.value, made.value, input.labels);
242
+ if (made.error.kind !== "invalid")
243
+ return made.error;
244
+ const open = await github(ctx, "GET", `/repos/${repo.value}/pulls?state=open&head=${headOf(repo.value, input.branch)}`, z.array(pull));
245
+ if (!open.ok)
246
+ return open.error;
247
+ const [existing] = open.value;
248
+ return existing === undefined
249
+ ? made.error
250
+ : await labelled(ctx, repo.value, existing, input.labels);
251
+ },
252
+ }),
253
+ /** The review line of the first body is left out: that review read the change before this one. */
254
+ update_pull_request: defineTool({
255
+ description: "Give an open pull request a new title and body when a later change made them untrue; skipped when it is merged or closed",
256
+ input: updatePullRequest.input,
257
+ output: updatePullRequest.output,
258
+ ...apiAccess,
259
+ side_effect: true,
260
+ undo: "none",
261
+ undo_reason: "The new title and body describe what the pull request holds, and they stay true when a later stage is undone.",
262
+ execute: async (input, ctx) => {
263
+ const settings = config.safeParse(ctx.config ?? {});
264
+ if (!settings.success) {
265
+ return permanentFailure("invalid", "the [extensions.github] table does not match its schema");
266
+ }
267
+ const path = pullOf(input.url);
268
+ if (!path.ok)
269
+ return path.error;
270
+ const read = await github(ctx, "GET", path.value, pullBody);
271
+ if (!read.ok)
272
+ return read.error;
273
+ if (stateOf(read.value) !== "open")
274
+ return skipped();
275
+ const repo = path.value.split("/").slice(2, 4).join("/");
276
+ const base = settings.data.default_base;
277
+ const notes = await noticesOf(ctx, repo, base, { ...input, branch: read.value.head.ref });
278
+ const updated = await github(ctx, "PATCH", path.value, pull, {
279
+ title: input.title,
280
+ body: bodyOf(input.body, ...notes, ...proofOf(input.checks, input.not_verified), screenshotOf(read.value.body ?? "") ?? "", `edgar-operation: ${ctx.operation_id}`),
281
+ });
282
+ return updated.ok ? done({ url: updated.value.html_url }) : updated.error;
283
+ },
284
+ }),
285
+ /** The picture goes to the branch `edgar/screenshots` of the same repository, never to the pull request's branch, and the body shows it pinned to the commit that holds it, to each person who can see the pull request. A picture that is missing, too large or not stored still gives the body one line that says why, and the outcome says it too; only an input that is not a pull request fails. */
286
+ attach_screenshot: defineTool({
287
+ description: "Put a screenshot from the sandbox into a pull request's body, stored on the edgar/screenshots branch, or say in the body why it is missing",
288
+ input: attachScreenshot.input,
289
+ output: attachScreenshot.output,
290
+ ...apiAccess,
291
+ capabilities: [...apiAccess.capabilities, "sandbox:read"],
292
+ side_effect: true,
293
+ undo: "none",
294
+ undo_reason: "The picture shows the change that the pull request holds, and it stays true when a later stage is undone.",
295
+ execute: async ({ url, shot }, ctx) => {
296
+ const path = pullOf(url);
297
+ if (!path.ok)
298
+ return path.error;
299
+ const repo = path.value.split("/").slice(2, 4).join("/");
300
+ const shown = await picture(ctx, repo, shot);
301
+ const text = shown.ok ? shown.value.text : `The screenshot is missing: ${shown.error}.`;
302
+ const read = await github(ctx, "GET", path.value, pullBody);
303
+ const written = read.ok
304
+ ? await github(ctx, "PATCH", path.value, pull, {
305
+ body: withScreenshot(read.value.body ?? "", text),
306
+ })
307
+ : read;
308
+ if (!written.ok) {
309
+ const why = shown.ok ? "the picture is stored" : shown.error;
310
+ return done({
311
+ attached: false,
312
+ missing: `${why}; the body was not changed: ${said(written.error)}`,
313
+ });
314
+ }
315
+ return done(shown.ok
316
+ ? { attached: true, image: shown.value.image }
317
+ : { attached: false, missing: shown.error });
318
+ },
319
+ }),
320
+ close_pull_request: defineTool({
321
+ description: "Close a pull request without merging it; skipped when it is merged or closed",
322
+ input: closePullRequest.input,
323
+ output: closePullRequest.output,
324
+ ...apiAccess,
325
+ execute: async ({ stage_output, text }, ctx) => {
326
+ const path = pullOf(stage_output.url);
327
+ if (!path.ok)
328
+ return path.error;
329
+ const read = await github(ctx, "GET", path.value, pull);
330
+ if (!read.ok)
331
+ return read.error;
332
+ if (stateOf(read.value) !== "open")
333
+ return skipped();
334
+ if (text !== undefined) {
335
+ const said = await noted(ctx, path.value, text);
336
+ if (said.outcome !== "done")
337
+ return said;
338
+ }
339
+ const closed = await github(ctx, "PATCH", path.value, pull, { state: "closed" });
340
+ if (!closed.ok)
341
+ return closed.error;
342
+ return done({ url: closed.value.html_url, state: stateOf(closed.value) });
343
+ },
344
+ }),
345
+ /** One comment on the pull request holds every line, so a person reads what EDGAR did there in one place and gets no comment for each step. The comment is found by its first line. A call whose line is already the last line writes nothing, so a retry after a lost answer adds no second line. shortcut: the oldest 100 comments are read, so a note after them is not found and a second one is made; upgrade to `Link` pagination when a pull request holds more. */
346
+ note_pull_request: defineTool({
347
+ description: "Add a line to EDGAR's one note on a pull request: what failed there, what EDGAR does about it, what it changed",
348
+ input: notePullRequest.input,
349
+ output: notePullRequest.output,
350
+ ...apiAccess,
351
+ side_effect: true,
352
+ undo: "none",
353
+ undo_reason: "A line of the note says what happened on the pull request, and it stays true when a later stage is undone.",
354
+ execute: async ({ url, text }, ctx) => {
355
+ const path = pullOf(url);
356
+ return path.ok ? await noted(ctx, path.value, text) : path.error;
357
+ },
358
+ }),
359
+ /** Only the pull requests of `repo` are read, so a card cannot bring code from another repository into the project's tracker. A link that answers 404 or 403 is left out, because a pull request EDGAR cannot read is no reason to stop the work on the card. shortcut: the first 5 links, 100 files each, and 4,000 characters of each patch; upgrade to paging when a linked fix is larger. */
360
+ linked_pull_requests: defineTool({
361
+ description: "Read the pull requests of the repository that a text links, with the state, description and diff of each; skipped when it links none",
362
+ input: linkedPullRequests.input,
363
+ output: linkedPullRequests.output,
364
+ ...apiAccess,
365
+ execute: async ({ text, repo }, ctx) => {
366
+ const own = repoPath(repo);
367
+ const paths = new Set();
368
+ for (const [link, linked, number] of text.matchAll(/https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g)) {
369
+ if (own !== undefined && repoPath(linked ?? "") === own) {
370
+ paths.add(`/repos/${own}/pulls/${number ?? ""}`);
371
+ }
372
+ else {
373
+ ctx.log(`${link} left out of the linked pull requests: it is not in ${repo}`);
374
+ }
375
+ }
376
+ if (paths.size === 0)
377
+ return skipped();
378
+ const pullRequests = [];
379
+ for (const path of [...paths].slice(0, 5)) {
380
+ const read = await github(ctx, "GET", path, linkedPull);
381
+ if (!read.ok && (read.error.kind === "not_found" || read.error.kind === "forbidden")) {
382
+ ctx.log(`${path} left out of the linked pull requests: ${read.error.message}`);
383
+ continue;
384
+ }
385
+ if (!read.ok)
386
+ return read.error;
387
+ const files = await github(ctx, "GET", `${path}/files?per_page=100`, z.array(pullFile));
388
+ if (!files.ok)
389
+ return files.error;
390
+ pullRequests.push({
391
+ url: read.value.html_url,
392
+ state: stateOf(read.value),
393
+ title: read.value.title,
394
+ body: read.value.body ?? "",
395
+ files: files.value.map((file) => ({
396
+ path: file.filename,
397
+ patch: (file.patch ?? "").slice(0, 4000),
398
+ })),
399
+ });
400
+ }
401
+ return done({ pull_requests: pullRequests });
402
+ },
403
+ }),
404
+ find_pull_request: defineTool({
405
+ description: "Find the pull request of a branch; skipped when there is none",
406
+ input: findPullRequest.input,
407
+ output: findPullRequest.output,
408
+ ...apiAccess,
409
+ execute: async ({ input }, ctx) => {
410
+ const repo = repoOf(input.repo);
411
+ if (!repo.ok)
412
+ return repo.error;
413
+ const found = await github(ctx, "GET", `/repos/${repo.value}/pulls?state=all&head=${headOf(repo.value, input.branch)}`, z.array(pull));
414
+ if (!found.ok)
415
+ return found.error;
416
+ const [first] = found.value;
417
+ return first === undefined ? skipped() : done({ url: first.html_url, state: stateOf(first) });
418
+ },
419
+ }),
420
+ /** A pull request whose head is in another repository, such as a fork, is left out: its branch name proves nothing. shortcut: one page of 100 per repository, so with `merged_within_hours` a merge past the 100 closed pull requests updated last is not read; upgrade to `Link` pagination when a repository closes more within the window. */
421
+ list_pull_requests: defineTool({
422
+ description: "List the open pull requests on edgar/ branches of each service's repository on github.com, or with merged_within_hours the ones merged within that many hours; a service elsewhere has none here",
423
+ input: listPullRequests.input,
424
+ output: listPullRequests.output,
425
+ ...apiAccess,
426
+ execute: async ({ services, merged_within_hours }, ctx) => {
427
+ const repos = new Set();
428
+ for (const service of services) {
429
+ const repo = repoPath(service.repo);
430
+ if (repo !== undefined)
431
+ repos.add(repo);
432
+ }
433
+ const since = merged_within_hours === undefined
434
+ ? undefined
435
+ : Date.now() - merged_within_hours * 3_600_000;
436
+ const query = since === undefined
437
+ ? "state=open&per_page=100"
438
+ : "state=closed&sort=updated&direction=desc&per_page=100";
439
+ const pull_requests = [];
440
+ for (const repo of repos) {
441
+ const listed = await github(ctx, "GET", `/repos/${repo}/pulls?${query}`, z.array(pullBody));
442
+ if (!listed.ok)
443
+ return listed.error;
444
+ for (const p of listed.value) {
445
+ const card = cardOf(p.head.ref);
446
+ const own = p.head.repo?.full_name.toLowerCase() === repo;
447
+ const kept = since === undefined || (p.merged_at !== null && Date.parse(p.merged_at) >= since);
448
+ if (card === null || !own || !kept)
449
+ continue;
450
+ const unmerged = since === undefined ? ok([]) : await unmergedOf(ctx, p.body);
451
+ if (!unmerged.ok)
452
+ return unmerged.error;
453
+ pull_requests.push({
454
+ url: p.html_url,
455
+ branch: p.head.ref,
456
+ card,
457
+ unmerged: unmerged.value,
458
+ });
459
+ }
460
+ }
461
+ return done({ pull_requests });
462
+ },
463
+ }),
464
+ pull_request_state: defineTool({
465
+ description: "Read a pull request's state, its review state, who approved it, its card, its commit, and its head branch and repository",
466
+ input: pullRequestState.input,
467
+ output: pullRequestState.output,
468
+ ...apiAccess,
469
+ execute: ({ url }, ctx) => stateOfPull(ctx, url),
470
+ }),
471
+ /** The recheck of a `wait` stage: a recheck's `done` ends the wait, so an open pull request with no deciding review answers `skipped`. */
472
+ wait_for_review: defineTool({
473
+ description: "As pull_request_state, for a wait stage's recheck: skipped while the pull request is open and no review has decided, done once it is approved, has a change request, or is merged or closed",
474
+ input: pullRequestState.input,
475
+ output: pullRequestState.output,
476
+ ...apiAccess,
477
+ execute: async ({ url }, ctx) => {
478
+ const read = await stateOfPull(ctx, url);
479
+ const undecided = read.outcome === "done" &&
480
+ read.output.state === "open" &&
481
+ read.output.review_state === "pending";
482
+ return undecided ? skipped() : read;
483
+ },
484
+ }),
485
+ /** The recheck of a `wait` stage that ends on the merge or the close of a pull request, and on nothing else, so an approval does not end it. */
486
+ wait_for_merge: defineTool({
487
+ description: "For a wait stage's recheck: skipped while the pull request is open, done with the merge commit once it is merged, and done with merged false once it is closed without a merge",
488
+ input: waitForMerge.input,
489
+ output: waitForMerge.output,
490
+ ...apiAccess,
491
+ execute: async ({ url }, ctx) => {
492
+ const path = pullOf(url);
493
+ if (!path.ok)
494
+ return path.error;
495
+ const read = await github(ctx, "GET", path.value, pull);
496
+ if (!read.ok)
497
+ return read.error;
498
+ const p = read.value;
499
+ if (p.merged_at !== null)
500
+ return done({ url, merged: true, sha: p.merge_commit_sha ?? p.head.sha });
501
+ return p.state === "open" ? skipped() : done({ url, merged: false });
502
+ },
503
+ }),
504
+ /** Merges `commit` only: the approval a person gave covers that commit, and GitHub answers 409 when the head has moved. A retry after a lost answer gets 405 for the merge its earlier attempt made: a `tool_error` reads the pull request back and returns its merge commit when it is merged at `commit`; a merge at another head is `invalid`. */
505
+ merge_pull_request: disableTool(defineTool({
506
+ description: "Merge a pull request; every call needs a person's approval",
507
+ input: mergePullRequest.input,
508
+ output: mergePullRequest.output,
509
+ ...apiAccess,
510
+ side_effect: true,
511
+ undo: "none",
512
+ undo_reason: "a merged pull request cannot be unmerged; a revert is a new change",
513
+ approval: "always",
514
+ execute: async ({ url, commit }, ctx) => {
515
+ const path = pullOf(url);
516
+ if (!path.ok)
517
+ return path.error;
518
+ const merged = await github(ctx, "PUT", `${path.value}/merge`, merge, { sha: commit });
519
+ if (merged.ok)
520
+ return done({ url, merged: merged.value.merged, commit: merged.value.sha });
521
+ if (merged.error.kind !== "tool_error")
522
+ return merged.error;
523
+ const read = await github(ctx, "GET", path.value, pull);
524
+ if (!read.ok)
525
+ return read.error;
526
+ const head = read.value.head.sha;
527
+ const wasMerged = read.value.merged_at !== null;
528
+ if (head === commit)
529
+ return wasMerged
530
+ ? done({ url, merged: true, commit: read.value.merge_commit_sha ?? head })
531
+ : merged.error;
532
+ return permanentFailure("invalid", wasMerged
533
+ ? `github: ${url} was merged at ${head}, not at the approved commit ${commit}; a person reads what was merged`
534
+ : `github: the head of ${url} is no longer ${commit}, so nothing was merged; read pull_request_state and ask for the approval of the new commit`, merged.error.cause === undefined ? {} : { cause: merged.error.cause });
535
+ },
536
+ })),
537
+ };
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+ import { alert } from "#schemas/github";
3
+ import { dependabotAlerts } from "#schemas/tools";
4
+ type Alert = z.infer<typeof dependabotAlerts.output>["alerts"][number];
5
+ /** The facts a stage decides on, lifted out of GitHub's alert. */
6
+ export declare function factsOf(a: z.infer<typeof alert>): Alert;
7
+ /** The repository tools of the GitHub extension, by the name the manifest gives them. */
8
+ export declare const repositoryTools: {
9
+ /** shortcut: one page of up to 100 alerts, newest first; `ghsa` and `cve` match within that page, said by `complete`. */
10
+ dependabot_alerts: import("@kana-ai/edgar-sdk").Tool<{
11
+ repo: string;
12
+ number?: number | undefined;
13
+ state?: ("auto_dismissed" | "dismissed" | "fixed" | "open")[] | undefined;
14
+ package?: string | undefined;
15
+ ghsa?: string[] | undefined;
16
+ cve?: string[] | undefined;
17
+ limit?: number | undefined;
18
+ }, {
19
+ alerts: {
20
+ number: number;
21
+ url: string;
22
+ state: string;
23
+ package: string | null;
24
+ ecosystem: string | null;
25
+ severity: string;
26
+ vulnerable_range: string;
27
+ first_patched: string | null;
28
+ manifest: string | null;
29
+ scope: string | null;
30
+ ghsa: string;
31
+ cve: string | null;
32
+ summary: string;
33
+ }[];
34
+ complete: boolean;
35
+ }, "GITHUB_TOKEN">;
36
+ branch_protection: import("@kana-ai/edgar-sdk").Tool<{
37
+ repo: string;
38
+ branch: string;
39
+ }, {
40
+ branch: string;
41
+ protected: boolean;
42
+ pull_request_required: boolean | null;
43
+ required_approvals: number | null;
44
+ required_checks: string[];
45
+ rules: {
46
+ type: string;
47
+ ruleset_id: number;
48
+ source: string;
49
+ }[];
50
+ classic: "none" | "read" | "unreadable";
51
+ }, "GITHUB_TOKEN">;
52
+ };
53
+ export {};