@kana-ai/edgar-ext-github 0.1.2 → 0.1.4

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 (71) hide show
  1. package/README.md +130 -74
  2. package/dist/src/api/app.d.ts +25 -6
  3. package/dist/src/api/app.js +72 -9
  4. package/dist/src/api/client.d.ts +9 -6
  5. package/dist/src/api/client.js +58 -19
  6. package/dist/src/api/commits.d.ts +4 -0
  7. package/dist/src/api/commits.js +69 -0
  8. package/dist/src/api/failures.d.ts +4 -0
  9. package/dist/src/api/failures.js +14 -1
  10. package/dist/src/feed/alerts.d.ts +9 -3
  11. package/dist/src/feed/alerts.js +66 -6
  12. package/dist/src/feed/service.d.ts +10 -1
  13. package/dist/src/feed/service.js +79 -16
  14. package/dist/src/index.d.ts +97 -1
  15. package/dist/src/index.js +17 -4
  16. package/dist/src/schemas/config.d.ts +1 -0
  17. package/dist/src/schemas/config.js +73 -29
  18. package/dist/src/schemas/github.d.ts +121 -1
  19. package/dist/src/schemas/github.js +37 -2
  20. package/dist/src/schemas/tools.d.ts +159 -2
  21. package/dist/src/schemas/tools.js +129 -6
  22. package/dist/src/tools/alerts.js +1 -0
  23. package/dist/src/tools/branch.d.ts +12 -0
  24. package/dist/src/tools/branch.js +69 -1
  25. package/dist/src/tools/pull-request.d.ts +55 -7
  26. package/dist/src/tools/pull-request.js +131 -42
  27. package/dist/src/tools/revert.d.ts +27 -0
  28. package/dist/src/tools/revert.js +98 -0
  29. package/dist/src/tools/screenshot.d.ts +1 -1
  30. package/dist/src/tools/screenshot.js +25 -11
  31. package/dist/src/tracker/cards.d.ts +1 -1
  32. package/dist/src/tracker/cards.js +84 -8
  33. package/dist/src/tracker/comments.d.ts +14 -2
  34. package/dist/src/tracker/comments.js +100 -4
  35. package/dist/src/tracker/port.d.ts +1 -1
  36. package/dist/src/tracker/port.js +4 -6
  37. package/dist/src/tracker/read-link.d.ts +2 -0
  38. package/dist/src/tracker/read-link.js +23 -0
  39. package/dist/src/tracker/states.d.ts +14 -3
  40. package/dist/src/tracker/states.js +37 -6
  41. package/dist/src/tracker/tools.d.ts +27 -0
  42. package/dist/src/tracker/tools.js +63 -7
  43. package/dist/src/tracker/transitions.d.ts +14 -3
  44. package/dist/src/tracker/transitions.js +57 -10
  45. package/edgar-extension.json +121 -7
  46. package/package.json +3 -3
  47. package/schemas/attach_screenshot.in.json +19 -0
  48. package/schemas/config.json +49 -23
  49. package/schemas/create_card.in.json +4 -0
  50. package/schemas/delete_closed_branches.in.json +26 -0
  51. package/schemas/delete_closed_branches.out.json +22 -0
  52. package/schemas/find_revert_pull_request.in.json +21 -0
  53. package/schemas/find_revert_pull_request.out.json +14 -0
  54. package/schemas/list_pull_requests.out.json +5 -1
  55. package/schemas/mark_seen.in.json +11 -0
  56. package/schemas/mark_seen.out.json +10 -0
  57. package/schemas/merged_pull_request.in.json +17 -0
  58. package/schemas/merged_pull_request.out.json +18 -0
  59. package/schemas/open_pull_request.in.json +73 -1
  60. package/schemas/park.in.json +15 -0
  61. package/schemas/park.out.json +10 -0
  62. package/schemas/pull_request_state.out.json +10 -1
  63. package/schemas/release_follow_ups.in.json +5 -0
  64. package/schemas/retitle.in.json +16 -0
  65. package/schemas/retitle.out.json +13 -0
  66. package/schemas/revert_pull_request.in.json +11 -0
  67. package/schemas/revert_pull_request.out.json +14 -0
  68. package/schemas/set_priority.in.json +16 -0
  69. package/schemas/set_priority.out.json +10 -0
  70. package/schemas/update_pull_request.in.json +28 -1
  71. package/schemas/wait_for_review.out.json +10 -1
@@ -2,10 +2,11 @@ import { defineTool, disableTool, done, err, ok, permanentFailure, skipped, } fr
2
2
  import { z } from "zod";
3
3
  import { apiAccess, github } from "#api/client";
4
4
  import { config } from "#schemas/config";
5
- import { comparison, linkedPull, merge, note, pull, pullBody, pullFile, review, } from "#schemas/github";
5
+ import { basedPullBody, comparison, gitRef, linkedPull, merge, mergeablePull, note, pull, pullBody, pullFile, review, } from "#schemas/github";
6
6
  import { attachScreenshot, closePullRequest, findPullRequest, linkedPullRequests, listPullRequests, mergePullRequest, notePullRequest, openPullRequest, pullRequestState, updatePullRequest, waitForMerge, } from "#schemas/tools";
7
7
  import { picture, said, screenshotOf, withScreenshot } from "#tools/screenshot";
8
- function stateOf(value) {
8
+ /** A pull request's state, `merged` once it merged. */
9
+ export function stateOf(value) {
9
10
  return value.merged_at === null ? value.state : "merged";
10
11
  }
11
12
  /** `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. */
@@ -44,12 +45,19 @@ export function reviewState(reviews, head) {
44
45
  return "pending";
45
46
  return latest.some(({ state }) => state === "APPROVED") ? "approved" : "pending";
46
47
  }
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
+ /** The newest commit of `base`, the base branch of the pull request at the API `path`: the pull request's own `base.sha` can be older. */
49
+ async function baseCommit(ctx, path, base) {
50
+ const repo = path.replace(/\/pulls\/\d+$/, "");
51
+ const ref = base.split("/").map(encodeURIComponent).join("/");
52
+ const read = await github(ctx, "GET", `${repo}/git/ref/heads/${ref}`, gitRef);
53
+ return read.ok ? ok(read.value.object.sha) : read;
54
+ }
55
+ /** What `pull_request_state` answers: the pull request and its reviews in two reads, and the newest commit of its base in a third when it conflicts with it. shortcut: the oldest 100 reviews only, so a later approval is not read; upgrade to `Link` pagination when a pull request holds more. */
48
56
  async function stateOfPull(ctx, url) {
49
57
  const path = pullOf(url);
50
58
  if (!path.ok)
51
59
  return path.error;
52
- const read = await github(ctx, "GET", path.value, pull);
60
+ const read = await github(ctx, "GET", path.value, mergeablePull);
53
61
  if (!read.ok)
54
62
  return read.error;
55
63
  const reviews = await github(ctx, "GET", `${path.value}/reviews?per_page=100`, z.array(review));
@@ -57,6 +65,10 @@ async function stateOfPull(ctx, url) {
57
65
  return reviews.error;
58
66
  const p = read.value;
59
67
  const merged = p.merged_at !== null;
68
+ const mergeable = p.state === "open" ? p.mergeable : null;
69
+ const base = mergeable === false ? await baseCommit(ctx, path.value, p.base.ref) : undefined;
70
+ if (base !== undefined && !base.ok)
71
+ return base.error;
60
72
  return done({
61
73
  url: p.html_url,
62
74
  state: stateOf(p),
@@ -69,6 +81,8 @@ async function stateOfPull(ctx, url) {
69
81
  commit: merged ? (p.merge_commit_sha ?? p.head.sha) : p.head.sha,
70
82
  branch: p.head.ref,
71
83
  head_repo: p.head.repo?.full_name ?? null,
84
+ mergeable,
85
+ ...(base === undefined ? {} : { base_commit: base.value }),
72
86
  });
73
87
  }
74
88
  /** 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. */
@@ -105,7 +119,8 @@ export function pullOf(url) {
105
119
  ? err(permanentFailure("invalid_input", `${url} is not a github.com pull request URL`))
106
120
  : ok(path);
107
121
  }
108
- function headOf(repo, branch) {
122
+ /** The `head` query value of `branch` in `repo`, as `owner:branch`, encoded. */
123
+ export function headOf(repo, branch) {
109
124
  const [owner] = repo.split("/");
110
125
  return encodeURIComponent(`${owner ?? ""}:${branch}`);
111
126
  }
@@ -129,44 +144,107 @@ export function changeNotices(files, largeLines, paths) {
129
144
  const lines = files.reduce((sum, f) => sum + f.changes, 0);
130
145
  const plural = files.length === 1 ? "" : "s";
131
146
  const large = largeLines !== undefined && lines > largeLines
132
- ? [`**Large change.** ${String(lines)} lines across ${String(files.length)} file${plural}.`]
147
+ ? [
148
+ `This is a large change: ${String(lines)} lines across ${String(files.length)} file${plural}.`,
149
+ ]
133
150
  : [];
134
151
  const touched = paths
135
152
  .filter((p) => files.some((f) => f.filename.startsWith(p.prefix)))
136
153
  .map((p) => p.notice);
137
154
  return [...large, ...new Set(touched)];
138
155
  }
156
+ /** A pull request's title for its card, `<id>: <card title>`, so a reviewer sees the card at a glance; with no card, the title as written. */
157
+ export function titleOf(title, card) {
158
+ return card === undefined ? title : `${card.id}: ${card.title}`;
159
+ }
160
+ /** The first line of a body for its card: its link, or its id when the card has no address. */
161
+ export function cardLine(card) {
162
+ if (card === undefined)
163
+ return "";
164
+ return card.url === undefined ? `Card: ${card.id}` : `Card: [${card.id}](${card.url})`;
165
+ }
139
166
  function bodyOf(...parts) {
140
167
  return parts.filter((part) => part !== "").join("\n\n");
141
168
  }
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. */
169
+ /** The proof of a change as the body shows it. "Verified" lists each check that ended with exit code 0, and says when that was only on its second run, 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, and a failure that the check gave on the base commit too says that the change did not cause it. 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
170
  export function proofOf(checks, notVerified) {
144
171
  const results = checks?.results ?? [];
145
172
  const name = (check) => `\`${check.replaceAll("`", "")}\``;
146
- const passed = results.filter((r) => r.exit_code === 0).map((r) => `- ${name(r.check)} passed`);
173
+ const passed = results
174
+ .filter((r) => r.exit_code === 0)
175
+ .map((r) => r.runs === 2
176
+ ? `- ${name(r.check)} passed on its second run, after a failure`
177
+ : `- ${name(r.check)} passed`);
147
178
  const open = [
148
179
  ...results
149
180
  .filter((r) => r.exit_code !== 0)
150
181
  .map((r) => r.exit_code === null
151
182
  ? `- ${name(r.check)} did not run or did not end`
152
- : `- ${name(r.check)} ended with exit code ${String(r.exit_code)}`),
183
+ : r.pre_existing === true
184
+ ? `- ${name(r.check)} ended with exit code ${String(r.exit_code)}, and fails the same way on the base commit, so this change did not cause it`
185
+ : `- ${name(r.check)} ended with exit code ${String(r.exit_code)}`),
153
186
  ...(notVerified ?? [])
154
187
  .map((item) => item.trim().replaceAll(/\s+/g, " "))
155
188
  .filter((item) => item !== "")
156
189
  .map((item) => `- ${item}`),
157
190
  ];
158
- const none = results.length === 0
159
- ? "**Verified:** nothing was run. No check applies to this service."
160
- : "**Verified:** nothing passed.";
191
+ const none = results.length === 0 ? "Nothing was run. No check applies to this service." : "Nothing passed.";
161
192
  const verified = checks === undefined
162
193
  ? []
163
- : [passed.length === 0 ? none : ["**Verified:**", ...passed].join("\n")];
164
- const outstanding = notVerified === undefined ? [] : ["**Not verified:** nothing outstanding."];
194
+ : [section("Verified", passed.length === 0 ? none : passed.join("\n"))];
195
+ const outstanding = notVerified === undefined ? [] : [section("Not verified", "Nothing is outstanding.")];
165
196
  return [
166
197
  ...verified,
167
- ...(open.length === 0 ? outstanding : [["**Not verified:**", ...open].join("\n")]),
198
+ ...(open.length === 0 ? outstanding : [section("Not verified", open.join("\n"))]),
168
199
  ];
169
200
  }
201
+ /** A section of a body: a heading at the level that a pull request description starts its sections with, then its text. */
202
+ function section(heading, text) {
203
+ return `## ${heading}\n\n${text}`;
204
+ }
205
+ /** A fence for `text` that no run of backticks in it closes early. */
206
+ function fenced(text) {
207
+ const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((run) => run[0].length));
208
+ const fence = "`".repeat(longest + 1);
209
+ return `${fence}text\n${text}\n${fence}`;
210
+ }
211
+ /** What a proof that passed says by how it ended on the base commit: only a failure there proves the change. */
212
+ const onBase = {
213
+ failed: "It failed on the base commit and passes with the change, so it proves the change.",
214
+ passed: "It passes on the base commit too, so it does not show that the change is what makes it pass.",
215
+ unknown: "It passed, but I could not tell whether it fails on the base commit, so it does not prove the change.",
216
+ };
217
+ /** How the change's own proof ended, as advice that blocks nothing: the command, its outcome from the proof stage's exit code and from no words of a model, whether a proof that passed failed on the base commit, what the author said passing looks like, and the end of its output folded away. With no `proof`, the body says nothing of it. */
218
+ export function ownProofOf(proof, passes) {
219
+ if (proof === undefined)
220
+ return [];
221
+ const heading = "The change's own proof";
222
+ const command = proof.command.replaceAll("`", "");
223
+ const expected = passes === undefined ? "" : ` Passing looks like: ${passes.trim()}`;
224
+ const ended = proof.exit_code === null || proof.exit_code === undefined
225
+ ? "it was ended by a signal, such as its time limit"
226
+ : `it ended with exit code ${String(proof.exit_code)}`;
227
+ const tail = proof.output_tail === undefined || proof.output_tail === ""
228
+ ? ""
229
+ : `\n\n<details><summary>The end of its output</summary>\n\n${fenced(proof.output_tail)}\n\n</details>`;
230
+ const opening = proof.outcome === "failed" || proof.on_base === undefined
231
+ ? `It ${proof.outcome}, as advice that blocks nothing.`
232
+ : onBase[proof.on_base];
233
+ switch (proof.outcome) {
234
+ case "passed":
235
+ case "failed":
236
+ return [section(heading, `${opening} I ran \`${command}\`: ${ended}.${expected}${tail}`)];
237
+ case "not_run": {
238
+ const what = command === "" ? "the change's proof" : `\`${command}\``;
239
+ return [
240
+ section(heading, `It did not run, and blocks nothing. I could not run ${what}: ${proof.reason ?? "no reason was given"}.`),
241
+ ];
242
+ }
243
+ default:
244
+ proof.outcome;
245
+ throw new Error("unreachable");
246
+ }
247
+ }
170
248
  /** `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
249
  async function labelled(ctx, repo, made, labels) {
172
250
  if (labels !== undefined && labels.length > 0) {
@@ -176,9 +254,11 @@ async function labelled(ctx, repo, made, labels) {
176
254
  }
177
255
  return done({ url: made.html_url, number: made.number });
178
256
  }
179
- /** The first line of EDGAR's note on a pull request, which GitHub does not show, and the title under it. */
257
+ /** The most pull requests that one read of a list gives. */
258
+ const PAGE = 100;
259
+ /** The first line of EDGAR's note on a pull request, which GitHub does not show, and the sentence under it that leads its list. */
180
260
  const NOTE_MARK = "<!-- edgar:note -->";
181
- const NOTE_TITLE = "**EDGAR's notes on this pull request**";
261
+ const NOTE_LEAD = "EDGAR's notes on this pull request, oldest first:";
182
262
  /** 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
263
  async function noted(ctx, path, text) {
184
264
  const comments = `${path.replace("/pulls/", "/issues/")}/comments`;
@@ -193,7 +273,7 @@ async function noted(ctx, path, text) {
193
273
  const kept = read.value.find((comment) => comment.body?.startsWith(NOTE_MARK) === true);
194
274
  if (kept === undefined) {
195
275
  const made = await github(ctx, "POST", comments, note, {
196
- body: `${NOTE_MARK}\n${NOTE_TITLE}\n\n${line}`,
276
+ body: `${NOTE_MARK}\n${NOTE_LEAD}\n\n${line}`,
197
277
  });
198
278
  return made.ok ? done({ url: made.value.html_url }) : made.error;
199
279
  }
@@ -208,9 +288,10 @@ async function noted(ctx, path, text) {
208
288
  }
209
289
  /** The pull request tools of the GitHub extension, by the name the manifest gives them. */
210
290
  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. */
291
+ /** The pull request merges into `base`, the service's own default branch, else into `default_base`. 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
292
  open_pull_request: defineTool({
213
- description: "Open a pull request from a pushed edgar/ branch onto the default base",
293
+ publishes: true,
294
+ description: "Open a pull request from a pushed edgar/ branch onto base, else onto the default base",
214
295
  input: openPullRequest.input,
215
296
  output: openPullRequest.output,
216
297
  ...apiAccess,
@@ -225,20 +306,21 @@ export const pullRequestTools = {
225
306
  const repo = repoOf(input.repo);
226
307
  if (!repo.ok)
227
308
  return repo.error;
228
- const base = settings.data.default_base;
309
+ const base = input.base ?? settings.data.default_base;
229
310
  const notes = await noticesOf(ctx, repo.value, base, input);
230
311
  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 === ""
312
+ const body = bodyOf(cardLine(input.card), input.body, related.length === 0 ? "" : `Goes with: ${related.join(", ")}`, ...notes, ...proofOf(input.checks, input.not_verified), ...ownProofOf(input.proof, input.proof_passes), input.review === ""
232
313
  ? ""
233
314
  : `Before I opened this, a second model reviewed the change. ${input.review}`, `edgar-operation: ${ctx.operation_id}`);
315
+ const labels = [...new Set([...settings.data.pr_labels, ...(input.labels ?? [])])];
234
316
  const made = await github(ctx, "POST", `/repos/${repo.value}/pulls`, pull, {
235
- title: input.title,
317
+ title: titleOf(input.title, input.card),
236
318
  head: input.branch,
237
319
  base,
238
320
  body,
239
321
  });
240
322
  if (made.ok)
241
- return await labelled(ctx, repo.value, made.value, input.labels);
323
+ return await labelled(ctx, repo.value, made.value, labels);
242
324
  if (made.error.kind !== "invalid")
243
325
  return made.error;
244
326
  const open = await github(ctx, "GET", `/repos/${repo.value}/pulls?state=open&head=${headOf(repo.value, input.branch)}`, z.array(pull));
@@ -247,11 +329,12 @@ export const pullRequestTools = {
247
329
  const [existing] = open.value;
248
330
  return existing === undefined
249
331
  ? made.error
250
- : await labelled(ctx, repo.value, existing, input.labels);
332
+ : await labelled(ctx, repo.value, existing, labels);
251
333
  },
252
334
  }),
253
- /** The review line of the first body is left out: that review read the change before this one. */
335
+ /** The review line of the first body is left out: that review read the change before this one. The notices compare the change with the pull request's own base. */
254
336
  update_pull_request: defineTool({
337
+ publishes: true,
255
338
  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
339
  input: updatePullRequest.input,
257
340
  output: updatePullRequest.output,
@@ -260,24 +343,22 @@ export const pullRequestTools = {
260
343
  undo: "none",
261
344
  undo_reason: "The new title and body describe what the pull request holds, and they stay true when a later stage is undone.",
262
345
  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
346
  const path = pullOf(input.url);
268
347
  if (!path.ok)
269
348
  return path.error;
270
- const read = await github(ctx, "GET", path.value, pullBody);
349
+ const read = await github(ctx, "GET", path.value, basedPullBody);
271
350
  if (!read.ok)
272
351
  return read.error;
273
352
  if (stateOf(read.value) !== "open")
274
353
  return skipped();
275
354
  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 });
355
+ const notes = await noticesOf(ctx, repo, read.value.base.ref, {
356
+ ...input,
357
+ branch: read.value.head.ref,
358
+ });
278
359
  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}`),
360
+ title: titleOf(input.title, input.card),
361
+ body: bodyOf(cardLine(input.card), input.body, ...notes, ...proofOf(input.checks, input.not_verified), screenshotOf(read.value.body ?? "") ?? "", `edgar-operation: ${ctx.operation_id}`),
281
362
  });
282
363
  return updated.ok ? done({ url: updated.value.html_url }) : updated.error;
283
364
  },
@@ -318,6 +399,7 @@ export const pullRequestTools = {
318
399
  },
319
400
  }),
320
401
  close_pull_request: defineTool({
402
+ publishes: true,
321
403
  description: "Close a pull request without merging it; skipped when it is merged or closed",
322
404
  input: closePullRequest.input,
323
405
  output: closePullRequest.output,
@@ -344,6 +426,7 @@ export const pullRequestTools = {
344
426
  }),
345
427
  /** 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
428
  note_pull_request: defineTool({
429
+ publishes: true,
347
430
  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
431
  input: notePullRequest.input,
349
432
  output: notePullRequest.output,
@@ -417,7 +500,7 @@ export const pullRequestTools = {
417
500
  return first === undefined ? skipped() : done({ url: first.html_url, state: stateOf(first) });
418
501
  },
419
502
  }),
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. */
503
+ /** 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; a full page sets `complete` to false and logs the repository; upgrade to `Link` pagination when a repository closes more within the window. */
421
504
  list_pull_requests: defineTool({
422
505
  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
506
  input: listPullRequests.input,
@@ -434,13 +517,18 @@ export const pullRequestTools = {
434
517
  ? undefined
435
518
  : Date.now() - merged_within_hours * 3_600_000;
436
519
  const query = since === undefined
437
- ? "state=open&per_page=100"
438
- : "state=closed&sort=updated&direction=desc&per_page=100";
520
+ ? `state=open&per_page=${String(PAGE)}`
521
+ : `state=closed&sort=updated&direction=desc&per_page=${String(PAGE)}`;
439
522
  const pull_requests = [];
523
+ let complete = true;
440
524
  for (const repo of repos) {
441
525
  const listed = await github(ctx, "GET", `/repos/${repo}/pulls?${query}`, z.array(pullBody));
442
526
  if (!listed.ok)
443
527
  return listed.error;
528
+ if (listed.value.length === PAGE) {
529
+ complete = false;
530
+ ctx.log(`list_pull_requests read only the first ${String(PAGE)} pull requests of ${repo}; one past them is not listed`);
531
+ }
444
532
  for (const p of listed.value) {
445
533
  const card = cardOf(p.head.ref);
446
534
  const own = p.head.repo?.full_name.toLowerCase() === repo;
@@ -458,7 +546,7 @@ export const pullRequestTools = {
458
546
  });
459
547
  }
460
548
  }
461
- return done({ pull_requests });
549
+ return done({ pull_requests, complete });
462
550
  },
463
551
  }),
464
552
  pull_request_state: defineTool({
@@ -468,9 +556,9 @@ export const pullRequestTools = {
468
556
  ...apiAccess,
469
557
  execute: ({ url }, ctx) => stateOfPull(ctx, url),
470
558
  }),
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`. */
559
+ /** The recheck of a `wait` stage: a recheck's `done` ends the wait, so an open pull request with no deciding review and no conflict answers `skipped`. */
472
560
  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",
561
+ description: "As pull_request_state, for a wait stage's recheck: skipped while the pull request is open, no review has decided and it does not conflict with its base, done once it is approved, has a change request, conflicts, or is merged or closed",
474
562
  input: pullRequestState.input,
475
563
  output: pullRequestState.output,
476
564
  ...apiAccess,
@@ -478,7 +566,8 @@ export const pullRequestTools = {
478
566
  const read = await stateOfPull(ctx, url);
479
567
  const undecided = read.outcome === "done" &&
480
568
  read.output.state === "open" &&
481
- read.output.review_state === "pending";
569
+ read.output.review_state === "pending" &&
570
+ read.output.mergeable !== false;
482
571
  return undecided ? skipped() : read;
483
572
  },
484
573
  }),
@@ -0,0 +1,27 @@
1
+ /** Reverting a merge after an alert came back: find a card's merged pull request, open GitHub's revert of it, and find that revert again after a call whose answer was lost. A person merges a revert; no tool here merges. */
2
+ export declare const revertTools: {
3
+ /** shortcut: the 100 closed pull requests updated last, so a merge older than those is not found; upgrade to `Link` pagination when a repository closes more between a merge and its card's move. */
4
+ merged_pull_request: import("@kana-ai/edgar-sdk").Tool<{
5
+ repo: string;
6
+ card: string;
7
+ }, {
8
+ url: string;
9
+ merged_at: string;
10
+ commit: string;
11
+ }, "GITHUB_TOKEN">;
12
+ revert_pull_request: import("@kana-ai/edgar-sdk").Tool<{
13
+ url: string;
14
+ }, {
15
+ url: string;
16
+ state: "closed" | "merged" | "open";
17
+ }, "GITHUB_TOKEN">;
18
+ find_revert_pull_request: import("@kana-ai/edgar-sdk").Tool<{
19
+ operation_id: string;
20
+ input: {
21
+ url: string;
22
+ };
23
+ }, {
24
+ url: string;
25
+ state: "closed" | "merged" | "open";
26
+ }, "GITHUB_TOKEN">;
27
+ };
@@ -0,0 +1,98 @@
1
+ import { defineTool, done, failure, ok, skipped } from "@kana-ai/edgar-sdk";
2
+ import { apiAccess, github } from "#api/client";
3
+ import { graphqlFailure } from "#api/failures";
4
+ import { nodePull, pull, revertAnswer } from "#schemas/github";
5
+ import { findRevertPullRequest, mergedPullRequest, revertPullRequest } from "#schemas/tools";
6
+ import { cardOf, headOf, pullOf, repoOf, stateOf } from "#tools/pull-request";
7
+ const REVERT = "mutation($id: ID!, $body: String) { revertPullRequest(input: { pullRequestId: $id, body: $body }) { revertPullRequest { url } } }";
8
+ /** The revert of the pull request `p` at the API `path`, open or not, or `undefined`. shortcut: GitHub names a revert's branch `revert-<number>-<head branch>`, so a revert made with another branch name is not found; upgrade to a search of the pull requests that name `p` when one is made by hand. */
9
+ async function revertOf(ctx, path, p) {
10
+ const repo = path.replace(/^\/repos\//, "").replace(/\/pulls\/\d+$/, "");
11
+ const head = headOf(repo, `revert-${String(p.number)}-${p.head.ref}`);
12
+ const found = await github(ctx, "GET", `/repos/${repo}/pulls?state=all&head=${head}`, pull.array());
13
+ return found.ok ? ok(found.value[0]) : found;
14
+ }
15
+ /** Reverting a merge after an alert came back: find a card's merged pull request, open GitHub's revert of it, and find that revert again after a call whose answer was lost. A person merges a revert; no tool here merges. */
16
+ export const revertTools = {
17
+ /** shortcut: the 100 closed pull requests updated last, so a merge older than those is not found; upgrade to `Link` pagination when a repository closes more between a merge and its card's move. */
18
+ merged_pull_request: defineTool({
19
+ description: "The newest merged pull request of the card's edgar/ branch in the repository, with when it merged and its merge commit; skipped when there is none",
20
+ input: mergedPullRequest.input,
21
+ output: mergedPullRequest.output,
22
+ ...apiAccess,
23
+ execute: async (input, ctx) => {
24
+ const repo = repoOf(input.repo);
25
+ if (!repo.ok)
26
+ return repo.error;
27
+ const listed = await github(ctx, "GET", `/repos/${repo.value}/pulls?state=closed&sort=updated&direction=desc&per_page=100`, pull.array());
28
+ if (!listed.ok)
29
+ return listed.error;
30
+ const found = listed.value.find((p) => p.merged_at !== null &&
31
+ cardOf(p.head.ref) === input.card &&
32
+ p.head.repo?.full_name.toLowerCase() === repo.value);
33
+ if (found === undefined || found.merged_at === null)
34
+ return skipped();
35
+ return done({
36
+ url: found.html_url,
37
+ merged_at: found.merged_at,
38
+ commit: found.merge_commit_sha ?? found.head.sha,
39
+ });
40
+ },
41
+ }),
42
+ revert_pull_request: defineTool({
43
+ description: "Open GitHub's revert of a merged pull request, as a new pull request that a person merges; the revert already open when there is one; skipped when the pull request is not merged",
44
+ input: revertPullRequest.input,
45
+ output: revertPullRequest.output,
46
+ ...apiAccess,
47
+ side_effect: true,
48
+ compensate: "close_pull_request",
49
+ lookup: "find_revert_pull_request",
50
+ execute: async ({ url }, ctx) => {
51
+ const path = pullOf(url);
52
+ if (!path.ok)
53
+ return path.error;
54
+ const read = await github(ctx, "GET", path.value, nodePull);
55
+ if (!read.ok)
56
+ return read.error;
57
+ if (read.value.merged_at === null)
58
+ return skipped();
59
+ const known = await revertOf(ctx, path.value, read.value);
60
+ if (!known.ok)
61
+ return known.error;
62
+ if (known.value !== undefined)
63
+ return done({ url: known.value.html_url, state: stateOf(known.value) });
64
+ const body = `This reverts ${url}: an alert of the service came back after its merge. A person reviews and merges this revert; EDGAR does not.`;
65
+ const sent = await github(ctx, "POST", "/graphql", revertAnswer, { query: REVERT, variables: { id: read.value.node_id, body } }, path.value);
66
+ if (!sent.ok)
67
+ return sent.error;
68
+ const context = "github GraphQL revertPullRequest";
69
+ const errors = sent.value.errors ?? [];
70
+ if (errors.length > 0)
71
+ return graphqlFailure(errors, context);
72
+ const opened = sent.value.data?.revertPullRequest?.revertPullRequest?.url;
73
+ return opened === undefined
74
+ ? failure("tool_error", `${context}: unexpected answer`, { cause: "no pull request" })
75
+ : done({ url: opened, state: "open" });
76
+ },
77
+ }),
78
+ find_revert_pull_request: defineTool({
79
+ description: "Find the revert of a pull request; skipped when there is none",
80
+ input: findRevertPullRequest.input,
81
+ output: findRevertPullRequest.output,
82
+ ...apiAccess,
83
+ execute: async ({ input }, ctx) => {
84
+ const path = pullOf(input.url);
85
+ if (!path.ok)
86
+ return path.error;
87
+ const read = await github(ctx, "GET", path.value, pull);
88
+ if (!read.ok)
89
+ return read.error;
90
+ const known = await revertOf(ctx, path.value, read.value);
91
+ if (!known.ok)
92
+ return known.error;
93
+ return known.value === undefined
94
+ ? skipped()
95
+ : done({ url: known.value.html_url, state: stateOf(known.value) });
96
+ },
97
+ }),
98
+ };
@@ -13,7 +13,7 @@ export declare function screenshotOf(body: string): string | undefined;
13
13
  export declare function withScreenshot(body: string, text: string): string;
14
14
  /** A failure in one line that a person reads in a body. */
15
15
  export declare function said(failure: Failure): string;
16
- /** The Markdown of `shot` stored on the screenshots branch of `repo`, as an image pinned to the commit that holds it, or why there is none. */
16
+ /** The Markdown of `shot`: the address EDGAR serves it at when it is in the project's storage, else the picture stored on the screenshots branch of `repo`, pinned to the commit that holds it; or why there is none. A flow's video goes to the branch too, as a link under the picture, and a video that is not stored leaves a line that says why. */
17
17
  export declare function picture(ctx: Ctx<typeof TOKEN>, repo: string, shot: Shot): Promise<Result<{
18
18
  readonly image: string;
19
19
  readonly text: string;
@@ -78,22 +78,36 @@ async function stored(ctx, repo, file, content) {
78
78
  const sha = newest.ok ? newest.value[0]?.sha : undefined;
79
79
  return sha === undefined ? put : ok(sha);
80
80
  }
81
- /** The Markdown of `shot` stored on the screenshots branch of `repo`, as an image pinned to the commit that holds it, or why there is none. */
82
- export async function picture(ctx, repo, shot) {
83
- if ("missing" in shot)
84
- return err(shot.missing);
81
+ /** The file at `path` of the sandbox, stored on the screenshots branch of `repo` as `<run>/<name>-<hash>.<extension>`, at the address that shows it pinned to the commit that holds it; or why it is not. */
82
+ async function upload(ctx, repo, file, name, extension) {
85
83
  const kb = (bytes) => String(Math.ceil(bytes / 1024));
86
- if (shot.bytes > MAX_SCREENSHOT_BYTES) {
87
- return err(`it is ${kb(shot.bytes)} KB, over the ${kb(MAX_SCREENSHOT_BYTES)} KB a body shows`);
84
+ if (file.bytes > MAX_SCREENSHOT_BYTES) {
85
+ return err(`it is ${kb(file.bytes)} KB, over the ${kb(MAX_SCREENSHOT_BYTES)} KB a body shows`);
88
86
  }
89
- const read = await ctx.sandbox.read(shot.path, "base64");
87
+ const read = await ctx.sandbox.read(file.path, "base64");
90
88
  if (!read.ok)
91
89
  return err(`it could not be read from the sandbox: ${read.error.message}`);
92
90
  const hash = createHash("sha256").update(Buffer.from(read.value, "base64")).digest("hex");
93
- const file = `${ctx.run_id}/preview-${hash.slice(0, 16)}.png`;
94
- const commit = await stored(ctx, repo, file, read.value);
91
+ const at = `${ctx.run_id}/${name}-${hash.slice(0, 16)}.${extension}`;
92
+ const commit = await stored(ctx, repo, at, read.value);
95
93
  if (!commit.ok)
96
94
  return err(`the upload to GitHub failed: ${said(commit.error)}`);
97
- const image = `https://github.com/${repo}/blob/${commit.value}/${file}?raw=true`;
98
- return ok({ image, text: `![${shot.caption.replaceAll(/[[\]\n]/g, " ")}](${image})` });
95
+ return ok(`https://github.com/${repo}/blob/${commit.value}/${at}?raw=true`);
96
+ }
97
+ /** The Markdown of `shot`: the address EDGAR serves it at when it is in the project's storage, else the picture stored on the screenshots branch of `repo`, pinned to the commit that holds it; or why there is none. A flow's video goes to the branch too, as a link under the picture, and a video that is not stored leaves a line that says why. */
98
+ export async function picture(ctx, repo, shot) {
99
+ if ("missing" in shot)
100
+ return err(shot.missing);
101
+ const caption = shot.caption.replaceAll(/[[\]\n]/g, " ");
102
+ const image = shot.url === undefined ? await upload(ctx, repo, shot, "preview", "png") : ok(shot.url);
103
+ if (!image.ok)
104
+ return image;
105
+ const text = `![${caption}](${image.value})`;
106
+ if (shot.video === undefined)
107
+ return ok({ image: image.value, text });
108
+ const video = await upload(ctx, repo, shot.video, "flow", "mp4");
109
+ const line = video.ok
110
+ ? `[Watch the flow as a video](${video.value})`
111
+ : `The video is missing: ${video.error}.`;
112
+ return ok({ image: image.value, text: `${text}\n\n${line}` });
99
113
  }
@@ -24,7 +24,7 @@ export interface Found {
24
24
  }
25
25
  /** At most `max` open issues of the table's repositories that GitHub's search matches with `words`, the best match first; issues of other repositories are left out. */
26
26
  export declare function searchOpen(ctx: GithubCtx, settings: Settings, words: string, max: number): Promise<Result<Found[], Failure>>;
27
- /** Files an issue inside the table's scope, or returns the open issue that already holds the block's fingerprint, counting one more sighting on it. The issue goes to the repository of the block's service, else the first; it gets `title_prefix`, `labels` and the label of `spec.column`, and with `assignee_only`, `assignee`. A retry finds the issue its first call filed by the hidden marker of the operation among the newest 10 issues of the repository. Those 10 issues are also read for an open holder of the fingerprint that the search does not index yet, and calls with one fingerprint run one at a time in this process, so the second finds the issue the first filed. */
27
+ /** Files an issue inside the table's scope, or returns the open issue that already holds the block's fingerprint, counting one more sighting on it. With no open holder, an issue done less than `REOPEN_DAYS` ago that holds it is opened again in `ready`; else the new issue links the newest closed holder. The issue goes to the repository of the block's service, else the first; it gets `title_prefix`, `labels` and the label of `spec.column`, and never a priority label, which only a person or `set_priority` adds, and with `assignee_only`, `assignee`. A retry finds the issue its first call filed by the hidden marker of the operation among the newest 10 issues of the repository. Those 10 issues are also read for an open holder of the fingerprint that the search does not index yet, and calls with one fingerprint run one at a time in this process, so the second finds the issue the first filed. */
28
28
  export declare function createCard(ctx: GithubCtx, spec: CardSpec): Promise<Outcome<{
29
29
  id: string;
30
30
  url: string;