@notation/factory-github 0.5.4 → 0.5.5

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.
@@ -18,12 +18,21 @@ export const user = (login: string): AuthorSet => ({ kind: "user", login });
18
18
  /** Required: nothing is trusted by default. */
19
19
  const from = v.union([authorSet, v.array(authorSet)]);
20
20
 
21
+ /**
22
+ * With `mention`: the label that a run started by a mention adds to the
23
+ * issue. While the issue has the label, a new comment matches without the
24
+ * mention. Defaults to `listen:<mention without @>`. `false` adds no label.
25
+ * GitHub limits label names to 50 characters.
26
+ */
27
+ const listen = v.optional(v.union([v.pipe(v.string(), v.minLength(1), v.maxLength(50)), v.literal(false)]));
28
+
21
29
  export const issueSelector = v.object({
22
30
  actions: v.optional(
23
31
  v.array(v.picklist(["opened", "edited", "reopened", "labeled"])),
24
32
  ["opened"],
25
33
  ),
26
34
  mention: v.optional(v.string()),
35
+ listen,
27
36
  labels: v.optional(v.array(v.string())),
28
37
  from,
29
38
  });
@@ -32,6 +41,7 @@ export type IssueSelector = v.InferInput<typeof issueSelector>;
32
41
  export const issueCommentSelector = v.object({
33
42
  actions: v.optional(v.array(v.picklist(["created", "edited"])), ["created"]),
34
43
  mention: v.optional(v.string()),
44
+ listen,
35
45
  labels: v.optional(v.array(v.string())),
36
46
  from,
37
47
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory-github",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,9 +32,9 @@
32
32
  "valibot": "^1.1.0"
33
33
  },
34
34
  "peerDependencies": {
35
- "@notation/factory": "^0.5.4"
35
+ "@notation/factory": "^0.5.5"
36
36
  },
37
37
  "devDependencies": {
38
- "@notation/factory": "0.5.4"
38
+ "@notation/factory": "0.5.5"
39
39
  }
40
40
  }
@@ -146,10 +146,10 @@ test("a team in from leaves a check for the router to make", () => {
146
146
  );
147
147
  });
148
148
 
149
- test("labels must all be on the issue", () => {
149
+ test("labels must all be on the issue, in any case", () => {
150
150
  const labelled = selector({ labels: ["bug", "p1"] });
151
151
  assert.equal(channel.match(labelled, delivery({ labels: ["bug"] })), undefined);
152
- assert.ok(channel.match(labelled, delivery({ labels: ["bug", "p1"] })));
152
+ assert.ok(channel.match(labelled, delivery({ labels: ["bug", "P1"] })));
153
153
  });
154
154
 
155
155
  test("an edit matches only if it newly adds the mention", () => {
@@ -158,6 +158,37 @@ test("an edit matches only if it newly adds the mention", () => {
158
158
  assert.equal(channel.match(selector(), edit("@claude fix")), undefined);
159
159
  });
160
160
 
161
+ test("on an issue with the listen label, a new comment matches without the mention", () => {
162
+ const comment = (labels: string[]) => delivery({ body: "and the tests", before: "and the tests", labels });
163
+ assert.equal(channel.match(selector(), comment([])), undefined);
164
+ assert.ok(channel.match(selector(), comment(["listen:claude"])));
165
+ assert.ok(channel.match(selector({ listen: "agent" }), comment(["Agent"])));
166
+ assert.equal(channel.match(selector({ listen: false }), comment(["listen:claude"])), undefined);
167
+ assert.equal(channel.match(selector(), delivery({ action: "edited", body: "fix", before: "fixx", labels: ["listen:claude"] })), undefined);
168
+ assert.ok(channel.match(selector(), delivery({ labels: ["listen:claude"] })));
169
+ });
170
+
171
+ test("on an issue with the listen label, a comment addressed to someone else doesn't match", () => {
172
+ const comment = (body: string) => delivery({ body, before: body, labels: ["listen:claude"] });
173
+ assert.equal(channel.match(selector(), comment("@droid do it")), undefined);
174
+ assert.equal(channel.match(selector(), comment("what do you think, @bob?")), undefined);
175
+ assert.equal(channel.match(selector(), comment("ping @acme/core")), undefined);
176
+ assert.ok(channel.match(selector(), comment("mail me@example.com")));
177
+ assert.ok(channel.match(selector(), comment("@Claude and @claude again")));
178
+ assert.ok(channel.match(selector(), comment("fix the `@types/node` import")));
179
+ assert.ok(channel.match(selector(), comment("```ts\n@Injectable()\n```\nlike this")));
180
+ assert.ok(channel.match(selector(), comment("> @bob said x\n\nplease do it")));
181
+ });
182
+
183
+ test("the default listen label is cut to GitHub's 50 characters", async () => {
184
+ await withGithub({}, async (_, writes) => {
185
+ const d = await accepted("issue_comment", commentPayload);
186
+ await keyed.acknowledge!(d, [selector({ mention: "@some-org/a-very-long-team-name-that-goes-on-and-on" })]);
187
+ const [, , body] = writes.find(([, path]) => path.endsWith("/labels"))!;
188
+ assert.equal((body as { labels: string[] }).labels[0]!.length, 50);
189
+ });
190
+ });
191
+
161
192
  test("mentions match as GitHub does", () => {
162
193
  assert.equal(mentions("@Claude please", "@claude"), true);
163
194
  assert.equal(mentions("hi (@claude)", "@claude"), true);
@@ -205,7 +236,7 @@ const withGithub = async (
205
236
  const name = roles[decodeURIComponent(role[1]!)];
206
237
  return name ? Response.json({ permission: name, role_name: name }) : new Response("Not Found", { status: 404 });
207
238
  }
208
- if (init?.method === "PATCH" || url.pathname.endsWith("/reactions")) {
239
+ if (init?.method === "PATCH" || url.pathname.endsWith("/reactions") || url.pathname.endsWith("/labels")) {
209
240
  writes.push([init!.method!, url.pathname, JSON.parse(String(init!.body))]);
210
241
  if (deleted.some((id) => url.pathname.endsWith(`/comments/${id}`))) return new Response("Not Found", { status: 404 });
211
242
  return Response.json({});
@@ -359,12 +390,29 @@ test("a reply to a comment that's gone posts a new comment", async () => {
359
390
 
360
391
  test("acknowledge reacts with 👀 to the comment that matched, or to the issue for an issue event", async () => {
361
392
  await withGithub({}, async (_, writes) => {
362
- await keyed.acknowledge!(await accepted("issue_comment", commentPayload));
393
+ await keyed.acknowledge!(await accepted("issue_comment", commentPayload), []);
363
394
  const opened = { action: "opened", repository: commentPayload.repository, issue: commentPayload.issue };
364
- await keyed.acknowledge!(await accepted("issues", opened));
395
+ await keyed.acknowledge!(await accepted("issues", opened), []);
365
396
  assert.deepEqual(writes, [
366
397
  ["POST", "/repos/acme/api/issues/comments/99/reactions", { content: "eyes" }],
367
398
  ["POST", "/repos/acme/api/issues/7/reactions", { content: "eyes" }],
368
399
  ]);
369
400
  });
370
401
  });
402
+
403
+ test("acknowledge adds the listen label of each selector that listens", async () => {
404
+ await withGithub({}, async (_, writes) => {
405
+ const d = await accepted("issue_comment", commentPayload);
406
+ await keyed.acknowledge!(d, [selector(), selector({ mention: "@cursor", listen: false })]);
407
+ const labelled = writes.filter(([, path]) => path.endsWith("/labels"));
408
+ assert.deepEqual(labelled, [["POST", "/repos/acme/api/issues/7/labels", { labels: ["listen:claude"] }]]);
409
+ });
410
+ });
411
+
412
+ test("acknowledge adds no label that the issue has", async () => {
413
+ await withGithub({}, async (_, writes) => {
414
+ const d = await accepted("issue_comment", commentPayload);
415
+ await keyed.acknowledge!({ ...d, data: { ...d.data, labels: ["Listen:Claude"] } }, [selector()]);
416
+ assert.equal(writes.filter(([, path]) => path.endsWith("/labels")).length, 0);
417
+ });
418
+ });
package/router/index.ts CHANGED
@@ -12,6 +12,7 @@ import type { AuthorSet } from "../implementations/selectors.ts";
12
12
  import { appJwt } from "./app-jwt.ts";
13
13
  import { signIn, signInUrl } from "./operators.ts";
14
14
  import {
15
+ addLabels,
15
16
  comment,
16
17
  installedRepos,
17
18
  type IssueComment,
@@ -205,19 +206,44 @@ export const mentions = (body: string, mention: string) =>
205
206
  type Selector = {
206
207
  actions: string[];
207
208
  mention?: string;
209
+ listen?: string | false;
208
210
  labels?: string[];
209
211
  from: AuthorSet | AuthorSet[];
210
212
  };
211
213
 
214
+ /** The label that keeps a mention selector listening, if it has one. Outposts deployed before `listen` existed get the default too. */
215
+ const listenLabel = (selector: Pick<Selector, "mention" | "listen">) => {
216
+ if (!selector.mention || selector.listen === false) return undefined;
217
+ // GitHub limits label names to 50 characters, which a team's mention can pass.
218
+ return selector.listen ?? `listen:${selector.mention.replace(/^@/, "")}`.slice(0, 50);
219
+ };
220
+
221
+ const hasLabel = (labels: string[], label: string) => labels.some((l) => l.toLowerCase() === label.toLowerCase());
222
+
223
+ const HANDLE = /(?<![\w@.-])@[\w-]+(?:\/[\w-]+)?/g;
224
+
225
+ /** Code and quoted lines, where an `@` isn't a mention. */
226
+ const NOT_MENTIONS = /```[\s\S]*?(?:```|(?![\s\S]))|`[^`\n]*`|^>.*$/gm;
227
+
228
+ /** Whether `body` mentions a user or team other than `mention`, outside code and quotes. */
229
+ const mentionsOther = (body: string, mention: string) => {
230
+ const own = mention.replace(/^@/, "").toLowerCase();
231
+ return (body.replace(NOT_MENTIONS, "").match(HANDLE) ?? []).some((h) => h.slice(1).toLowerCase() !== own);
232
+ };
233
+
234
+ /** Whether the event's body mentions `mention`. An edit counts only if it newly adds the mention. */
235
+ const newlyMentions = (event: GithubEvent, mention: string) =>
236
+ mentions(event.body, mention) && !(event.action === "edited" && mentions(event.before, mention));
237
+
212
238
  const selects = (selector: Selector, event: GithubEvent) => {
213
239
  if (!selector.actions.includes(event.action)) return false;
214
- if (selector.labels?.some((l) => !event.labels.includes(l))) return false;
215
- if (selector.mention) {
216
- if (!mentions(event.body, selector.mention)) return false;
217
- // An edit matches only if it newly adds the mention.
218
- if (event.action === "edited" && mentions(event.before, selector.mention)) {
219
- return false;
220
- }
240
+ if (selector.labels?.some((l) => !hasLabel(event.labels, l))) return false;
241
+ if (selector.mention && !newlyMentions(event, selector.mention)) {
242
+ // On an issue with the listen label, a new comment matches without the mention, unless it's addressed to someone else. Edits don't.
243
+ const label = listenLabel(selector);
244
+ const listening =
245
+ event.action === "created" && label !== undefined && hasLabel(event.labels, label) && !mentionsOther(event.body, selector.mention);
246
+ if (!listening) return false;
221
247
  }
222
248
  return true;
223
249
  };
@@ -356,9 +382,18 @@ export const channel = (ctx: ChannelContext): Channel<GithubEvent> => {
356
382
  return threadMessages(await auth(), thread as Thread);
357
383
  },
358
384
 
359
- async acknowledge(delivery) {
385
+ async acknowledge(delivery, selectors) {
360
386
  const payload = delivery.payload as Payload;
361
- await reactEyes(await auth(), delivery.repo, { issue: payload.issue.number, comment: payload.comment?.id });
387
+ const a = await auth();
388
+ const labels = new Set<string>();
389
+ for (const s of selectors as Selector[]) {
390
+ const label = listenLabel(s);
391
+ if (label && !hasLabel(delivery.data.labels, label)) labels.add(label);
392
+ }
393
+ await Promise.all([
394
+ reactEyes(a, delivery.repo, { issue: payload.issue.number, comment: payload.comment?.id }),
395
+ labels.size ? addLabels(a, delivery.repo, payload.issue.number, [...labels]) : undefined,
396
+ ]);
362
397
  },
363
398
 
364
399
  async reply(thread, text, message) {
package/router/repos.ts CHANGED
@@ -243,6 +243,13 @@ export const reactEyes = async (auth: AppAuth, repo: string, target: { issue: nu
243
243
  await ok(await github("POST", path, token, { body: { content: "eyes" } }), `POST ${path}`);
244
244
  };
245
245
 
246
+ /** Adds labels to an issue or a pull request. GitHub creates a label that the repo doesn't have yet. */
247
+ export const addLabels = async (auth: AppAuth, repo: string, issue: number, labels: string[]) => {
248
+ const token = await repoToken(auth, repo, { issues: "write" });
249
+ const path = `/repos/${repo}/issues/${issue}/labels`;
250
+ await ok(await github("POST", path, token, { body: { labels } }), `POST ${path}`);
251
+ };
252
+
246
253
  const fullNames = (repos: { full_name: string }[] | undefined) => (repos ?? []).map((r) => r.full_name);
247
254
 
248
255
  /**