co-maintainer 0.6.9 → 0.6.11

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 (66) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/ai/fake.d.ts +10 -1
  3. package/dist/src/ai/fake.js +39 -4
  4. package/dist/src/cli/args.js +2 -0
  5. package/dist/src/cli/command_json.d.ts +6 -0
  6. package/dist/src/cli/command_json.js +1 -0
  7. package/dist/src/cli/commands/probe.js +25 -0
  8. package/dist/src/cli/commands/registry.js +11 -0
  9. package/dist/src/cli/commands/review.js +5 -1
  10. package/dist/src/cli/commands/serve.js +4 -0
  11. package/dist/src/cli/commands/set.js +4 -2
  12. package/dist/src/cli/review_args.d.ts +9 -0
  13. package/dist/src/cli/review_args.js +36 -1
  14. package/dist/src/github/app.d.ts +4 -0
  15. package/dist/src/github/app.js +10 -1
  16. package/dist/src/github/permissions.js +40 -0
  17. package/dist/src/github/write_access.d.ts +7 -0
  18. package/dist/src/github/write_access.js +12 -0
  19. package/dist/src/local/git_ops.js +3 -2
  20. package/dist/src/local/git_revision.d.ts +5 -2
  21. package/dist/src/local/git_revision.js +17 -10
  22. package/dist/src/pr/reviewer.d.ts +2 -0
  23. package/dist/src/pr/reviewer.js +1 -1
  24. package/dist/src/remote/push_client.d.ts +7 -0
  25. package/dist/src/remote/push_client.js +287 -0
  26. package/dist/src/remote/server/routes.d.ts +1 -0
  27. package/dist/src/remote/server/routes.js +61 -4
  28. package/dist/src/remote/server/sync.js +11 -3
  29. package/dist/src/remote/validate.js +17 -0
  30. package/dist/src/review/carry_over.d.ts +2 -0
  31. package/dist/src/review/carry_over.js +33 -26
  32. package/dist/src/server/api/repos.js +13 -2
  33. package/dist/src/server/pages/layout.js +1 -0
  34. package/dist/src/server/pages/repo.d.ts +3 -1
  35. package/dist/src/server/pages/repo.js +4 -1
  36. package/dist/src/server/pages/repo_pushes.d.ts +7 -0
  37. package/dist/src/server/pages/repo_pushes.js +144 -0
  38. package/dist/src/server/pages/repo_settings.js +45 -1
  39. package/dist/src/server/pages/router.js +22 -3
  40. package/dist/src/server/webhook/index.js +8 -1
  41. package/dist/src/services/dashboard.d.ts +46 -0
  42. package/dist/src/services/dashboard.js +24 -0
  43. package/dist/src/services/jobs.js +10 -0
  44. package/dist/src/services/push_review.d.ts +51 -0
  45. package/dist/src/services/push_review.js +878 -0
  46. package/dist/src/services/review.d.ts +20 -3
  47. package/dist/src/services/review.js +112 -39
  48. package/dist/src/services/setup.js +21 -0
  49. package/dist/src/services/watch_comments.d.ts +10 -0
  50. package/dist/src/services/watch_comments.js +166 -0
  51. package/dist/src/services/watch_issues.d.ts +70 -0
  52. package/dist/src/services/watch_issues.js +266 -0
  53. package/dist/src/services/watch_notes.d.ts +8 -0
  54. package/dist/src/services/watch_notes.js +80 -0
  55. package/dist/src/services/watch_status.d.ts +25 -0
  56. package/dist/src/services/watch_status.js +101 -0
  57. package/dist/src/services/webhook.js +108 -8
  58. package/dist/src/store/migrations.js +63 -0
  59. package/dist/src/store/repos.d.ts +1 -1
  60. package/dist/src/store/rows.d.ts +6 -0
  61. package/dist/src/store/watch.d.ts +108 -0
  62. package/dist/src/store/watch.js +186 -0
  63. package/dist/src/types.d.ts +2 -0
  64. package/dist/src/util/repo_name.d.ts +2 -0
  65. package/dist/src/util/repo_name.js +56 -0
  66. package/package.json +1 -1
@@ -0,0 +1,266 @@
1
+ /** The GitHub side of commit watch issues: the words co-maintainer writes,
2
+ * opening, commenting on and closing an issue, and finding a tracked
3
+ * finding's code again in a later commit.
4
+ *
5
+ * Issues are written in English. A reply to a comment is written in the
6
+ * comment's language, which is the comment job's business, not this file's. */
7
+ import { normalizeAnchor, normalizePath } from "../review/revision.js";
8
+ import { stripSuggestion } from "../pr/suggestion.js";
9
+ import { redact } from "../util/redact.js";
10
+ export const ISSUE_LABEL = "co-maintainer";
11
+ export const ISSUE_SEVERITIES = new Set(["P0", "P1"]);
12
+ export const CLOSE_DENIED_COMMENT = "I tried to close this issue, but I do not have permission to close issues in this repository.";
13
+ export const NOTED_REPLY = "Noted, I will take this into account on the next sync.";
14
+ const LABEL_COLORS = {
15
+ [ISSUE_LABEL]: "1f883d",
16
+ "cm-P0": "b60205",
17
+ "cm-P1": "d93f0b",
18
+ };
19
+ export function shortSha(sha) {
20
+ return sha.slice(0, 7);
21
+ }
22
+ /** `abc1234..def5678`, the range a push review covered. */
23
+ export function pushRange(before, after) {
24
+ return `${shortSha(before)}..${shortSha(after)}`;
25
+ }
26
+ export function findingMarker(id) {
27
+ return `<!-- co-maintainer:finding ${id} -->`;
28
+ }
29
+ /** Model text goes to a public issue, so a secret it quoted is masked and a
30
+ * suggestion block, which only makes sense on a diff, is dropped. */
31
+ function clean(text) {
32
+ return redact(stripSuggestion(text)).trim();
33
+ }
34
+ /** The finding in a few words, for the issue title and for later prompts:
35
+ * the body's first line, which the review writes as one sentence naming the
36
+ * defect. The heading (`[P1 · blocking] \`path\`: \`symbol\``) is the
37
+ * fallback. */
38
+ export function findingSummary(heading, body) {
39
+ const first = clean(body)
40
+ .split("\n")
41
+ .map((line) => line.trim())
42
+ .find(Boolean);
43
+ const text = first ??
44
+ clean(heading)
45
+ .replace(/^\[P[0-3][^\]]*\]\s*/, "")
46
+ .replace(/`/g, "");
47
+ const flat = text.replace(/\s+/g, " ");
48
+ return flat.length > 200 ? `${flat.slice(0, 199)}…` : flat;
49
+ }
50
+ export function issueTitle(severity, summary) {
51
+ return `[${severity}] ${summary}`;
52
+ }
53
+ export function permalink(repo, sha, path, from, to) {
54
+ const lines = from && from > 0
55
+ ? to && to > from
56
+ ? `#L${from}-L${to}`
57
+ : `#L${from}`
58
+ : "";
59
+ return `https://github.com/${repo}/blob/${sha}/${path}${lines}`;
60
+ }
61
+ export function issueBody(input) {
62
+ const where = input.path
63
+ ? permalink(input.repo, input.after, input.path, input.lineFrom, input.lineTo)
64
+ : "the whole push";
65
+ return [
66
+ clean(input.body),
67
+ "",
68
+ `**Where:** ${where}`,
69
+ `**Push:** \`${pushRange(input.before, input.after)}\` on \`${input.branch}\``,
70
+ "",
71
+ "Feel free to ask questions here if you need more detail.",
72
+ "",
73
+ "Opened by co-maintainer commit watch review.",
74
+ findingMarker(input.id),
75
+ ].join("\n");
76
+ }
77
+ /** `commit` changed the finding's lines, `after` is the push. When they are
78
+ * the same commit it is written once. */
79
+ export function stillFoundComment(commit, after, range) {
80
+ const where = shortSha(commit) === shortSha(after)
81
+ ? shortSha(commit)
82
+ : `${shortSha(commit)} (push ${shortSha(after)})`;
83
+ return `change in ${where}: changed, still found by the review of ${range}`;
84
+ }
85
+ export function fixedComment(commit, range) {
86
+ return `change in ${shortSha(commit)}: changed, no longer found by the review of ${range}. Closing.`;
87
+ }
88
+ export function closedStillFoundComment(range) {
89
+ return `This issue was closed, but the review of push ${range} still finds the problem. If there is something I should know, please leave it as a comment.`;
90
+ }
91
+ function write(client, endpoint, body) {
92
+ if (!client.write)
93
+ throw new Error("this GitHub client cannot post");
94
+ return client.write(endpoint, body);
95
+ }
96
+ /** Creates each label the issue needs. A label that already exists answers
97
+ * 422, which is fine. */
98
+ export async function ensureLabels(client, repo, names) {
99
+ for (const name of names) {
100
+ try {
101
+ await write(client, `repos/${repo}/labels`, {
102
+ name,
103
+ color: LABEL_COLORS[name] ?? "ededed",
104
+ description: "co-maintainer commit watch",
105
+ });
106
+ }
107
+ catch (error) {
108
+ if (error.status !== 422)
109
+ throw error;
110
+ }
111
+ }
112
+ }
113
+ export async function openIssue(client, repo, input) {
114
+ const labels = [ISSUE_LABEL, `cm-${input.severity}`];
115
+ await ensureLabels(client, repo, labels);
116
+ const created = await write(client, `repos/${repo}/issues`, {
117
+ title: input.title,
118
+ body: input.body,
119
+ labels,
120
+ });
121
+ const number = Number(created.number ?? 0);
122
+ if (!Number.isSafeInteger(number) || number <= 0) {
123
+ throw new Error("GitHub did not return the new issue's number");
124
+ }
125
+ return number;
126
+ }
127
+ export async function commentOnIssue(client, repo, issueNumber, body) {
128
+ const posted = await write(client, `repos/${repo}/issues/${issueNumber}/comments`, { body });
129
+ return String(posted.id ?? "");
130
+ }
131
+ /** Closes the issue, or leaves the comment that says it could not. Returns
132
+ * whether it closed. */
133
+ export async function closeIssue(client, repo, issueNumber) {
134
+ try {
135
+ if (!client.patch)
136
+ throw Object.assign(new Error("no PATCH"), { status: 403 });
137
+ await client.patch(`repos/${repo}/issues/${issueNumber}`, {
138
+ state: "closed",
139
+ state_reason: "completed",
140
+ });
141
+ return true;
142
+ }
143
+ catch (error) {
144
+ const status = error.status;
145
+ if (status !== 403 && status !== 404)
146
+ throw error;
147
+ await commentOnIssue(client, repo, issueNumber, CLOSE_DENIED_COMMENT);
148
+ return false;
149
+ }
150
+ }
151
+ /** Whether the issue is open on GitHub, and when closed whether a bot (this
152
+ * App) closed it. */
153
+ export async function readIssueState(client, repo, issueNumber) {
154
+ try {
155
+ const issue = await client.request(`repos/${repo}/issues/${issueNumber}`);
156
+ const closedBy = issue.closed_by ?? undefined;
157
+ const login = String(closedBy?.login ?? "");
158
+ return {
159
+ open: issue.state === "open",
160
+ closedByBot: String(closedBy?.type ?? "") === "Bot" || login.endsWith("[bot]"),
161
+ };
162
+ }
163
+ catch {
164
+ return undefined;
165
+ }
166
+ }
167
+ /** A file's text at a commit (the default branch when `sha` is empty), or
168
+ * undefined when it is gone or unreadable. */
169
+ export async function fileAt(client, repo, path, sha) {
170
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
171
+ try {
172
+ const query = sha ? `?ref=${sha}` : "";
173
+ const file = await client.request(`repos/${repo}/contents/${encoded}` + query);
174
+ if (typeof file.content !== "string")
175
+ return undefined;
176
+ return Buffer.from(file.content, "base64").toString("utf8");
177
+ }
178
+ catch {
179
+ return undefined;
180
+ }
181
+ }
182
+ /** The newest commit at or before `sha` that touched `path`, which inside a
183
+ * push that changed the file is the commit that changed it. */
184
+ export async function lastCommitFor(client, repo, path, sha) {
185
+ try {
186
+ const commits = await client.request(`repos/${repo}/commits?sha=${sha}&path=${encodeURIComponent(path)}&per_page=1`);
187
+ const first = Array.isArray(commits) ? commits[0] : undefined;
188
+ return typeof first?.sha === "string" ? first.sha : undefined;
189
+ }
190
+ catch {
191
+ return undefined;
192
+ }
193
+ }
194
+ /** Where `anchor` sits in `content`, the closest match to `oldFrom` when it
195
+ * appears more than once. Blank lines are skipped on both sides, the same
196
+ * way `normalizeAnchor` drops them. */
197
+ export function locateAnchor(content, anchor, oldFrom) {
198
+ if (!anchor)
199
+ return undefined;
200
+ const want = normalizeAnchor(anchor).split("\n").filter(Boolean);
201
+ if (want.length === 0)
202
+ return undefined;
203
+ const lines = content
204
+ .split("\n")
205
+ .map((text, index) => ({
206
+ number: index + 1,
207
+ text: text.trim().replace(/\s+/g, " "),
208
+ }))
209
+ .filter((line) => line.text);
210
+ let best;
211
+ for (let i = 0; i + want.length <= lines.length; i++) {
212
+ let ok = true;
213
+ for (let j = 0; j < want.length; j++) {
214
+ if (lines[i + j].text !== want[j]) {
215
+ ok = false;
216
+ break;
217
+ }
218
+ }
219
+ if (!ok)
220
+ continue;
221
+ const from = lines[i].number;
222
+ const to = lines[i + want.length - 1].number;
223
+ const distance = Math.abs(from - oldFrom);
224
+ if (!best || distance < best.distance)
225
+ best = { from, to, distance };
226
+ }
227
+ return best ? { from: best.from, to: best.to } : undefined;
228
+ }
229
+ /** The new-file line numbers a patch adds or changes. */
230
+ export function changedLines(patch) {
231
+ const changed = new Set();
232
+ let next = 0;
233
+ for (const text of patch.split("\n")) {
234
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(text);
235
+ if (hunk) {
236
+ next = Number(hunk[1]);
237
+ continue;
238
+ }
239
+ if (next === 0)
240
+ continue;
241
+ if (text.startsWith("+"))
242
+ changed.add(next++);
243
+ else if (text.startsWith("-")) {
244
+ // A removed line changes the place where it was.
245
+ changed.add(next);
246
+ }
247
+ else if (!text.startsWith("\\"))
248
+ next++;
249
+ }
250
+ return changed;
251
+ }
252
+ /** The finding's code with line numbers and a few lines around it, for the
253
+ * known-issue check. */
254
+ export function excerpt(content, from, to) {
255
+ const lines = content.split("\n");
256
+ const start = Math.max(1, from - 5);
257
+ const end = Math.min(lines.length, Math.max(from, to) + 5);
258
+ const out = [];
259
+ for (let n = start; n <= end; n++) {
260
+ out.push(`${String(n).padStart(6)} ${lines[n - 1] ?? ""}`);
261
+ }
262
+ return out.join("\n");
263
+ }
264
+ export function samePath(a, b) {
265
+ return Boolean(a && b && normalizePath(a) === normalizePath(b));
266
+ }
@@ -0,0 +1,8 @@
1
+ import type { AiProvider, AiResponse } from "../types.ts";
2
+ /** Applies the notes left since the last sync and returns every note line,
3
+ * old and new, for the detailed guide. With no app.db (a CLI sync on another
4
+ * machine) there are no notes. */
5
+ export declare function applyWatchNotes(repo: string, lowAi: AiProvider, usage?: (response: AiResponse) => Promise<void> | void): Promise<string[]>;
6
+ /** The guide with its maintainer notes section replaced by `lines`. The
7
+ * section is always last and starts with a marker, so it can be found again. */
8
+ export declare function withMaintainerNotes(guide: string, lines: string[]): string;
@@ -0,0 +1,80 @@
1
+ /** What `sync` does with the notes maintainers left on commit watch issues.
2
+ *
3
+ * Each new note is turned into one guide line by the low model. The lines go
4
+ * into the detailed review guide, so every later review knows them. A note
5
+ * that said to ignore the finding also marks its issue ignored, the hard
6
+ * filter: no issue, comment or report for that finding again. */
7
+ import { getWatchIssue, listWatchNotes, markWatchNoteApplied, updateWatchIssue, } from "../store/watch.js";
8
+ import { log } from "../util/log.js";
9
+ const SECTION_START = "<!-- co-maintainer:maintainer-notes -->";
10
+ const SECTION_TITLE = "## Maintainer notes";
11
+ function notePrompt(note, issueTitle, path) {
12
+ return `A maintainer replied on an issue an automated code reviewer opened.
13
+ Turn the reply into one line for the repository's review guide: a general
14
+ statement a future reviewer must follow, in English, at most 200 characters,
15
+ with no names, mentions, issue numbers or quotes. Return only that line.
16
+
17
+ The reviewer had reported: ${issueTitle}${path ? ` (in ${path})` : ""}
18
+ The maintainer ${note.kind === "ignore" ? "said to ignore it" : "added information"}:
19
+ ${note.body.slice(0, 4000)}`;
20
+ }
21
+ function oneLine(text) {
22
+ return text
23
+ .replace(/```[\s\S]*?```/g, "")
24
+ .replace(/@[A-Za-z0-9_-]{2,}/g, "")
25
+ .replace(/\s+/g, " ")
26
+ .replace(/^[-*\s]+/, "")
27
+ .trim()
28
+ .slice(0, 300);
29
+ }
30
+ /** Applies the notes left since the last sync and returns every note line,
31
+ * old and new, for the detailed guide. With no app.db (a CLI sync on another
32
+ * machine) there are no notes. */
33
+ export async function applyWatchNotes(repo, lowAi, usage) {
34
+ let notes;
35
+ try {
36
+ notes = listWatchNotes(repo);
37
+ }
38
+ catch {
39
+ return [];
40
+ }
41
+ for (const note of notes) {
42
+ if (note.applied_at)
43
+ continue;
44
+ const issue = getWatchIssue(repo, note.issue_number);
45
+ const response = await lowAi.complete({
46
+ job: "watch_note",
47
+ prompt: notePrompt(note, issue?.title ?? "a finding", issue?.path ?? null),
48
+ maxTokens: 300,
49
+ });
50
+ await usage?.(response);
51
+ const line = oneLine(response.text) || oneLine(note.body);
52
+ const about = issue?.path ? ` (about \`${issue.path}\`)` : "";
53
+ note.note = `${line}${about}`;
54
+ markWatchNoteApplied(note.id, note.note);
55
+ if (note.kind === "ignore" && issue) {
56
+ updateWatchIssue(issue.id, { state: "ignored" });
57
+ }
58
+ log("write", `maintainer note from issue #${note.issue_number} added to the guide`);
59
+ }
60
+ return notes
61
+ .map((note) => note.note)
62
+ .filter((line) => Boolean(line));
63
+ }
64
+ /** The guide with its maintainer notes section replaced by `lines`. The
65
+ * section is always last and starts with a marker, so it can be found again. */
66
+ export function withMaintainerNotes(guide, lines) {
67
+ const at = guide.indexOf(SECTION_START);
68
+ const body = (at === -1 ? guide : guide.slice(0, at)).trimEnd();
69
+ if (lines.length === 0)
70
+ return body ? `${body}\n` : "";
71
+ const section = [
72
+ SECTION_START,
73
+ SECTION_TITLE,
74
+ "",
75
+ "Maintainers said these on commit watch issues. Follow them in every review.",
76
+ "",
77
+ ...lines.map((line) => `- ${line}`),
78
+ ].join("\n");
79
+ return body ? `${body}\n\n${section}\n` : `# Review notes\n\n${section}\n`;
80
+ }
@@ -0,0 +1,25 @@
1
+ import { type PushSource } from "../store/watch.ts";
2
+ import type { ReviewRow } from "../store/rows.ts";
3
+ export type AppPushState =
4
+ /** No App is configured, or GitHub could not be asked. */
5
+ "unknown"
6
+ /** No installation of the App covers the repository. */
7
+ | "not-installed" | "off" | "on";
8
+ export type WatchStatus = {
9
+ app: AppPushState;
10
+ /** A CI step has sent at least one push. */
11
+ ci: boolean;
12
+ lastPush: (ReviewRow & {
13
+ via: PushSource[];
14
+ }) | undefined;
15
+ };
16
+ /** For tests: forget what GitHub said. */
17
+ export declare function clearWatchStatusCache(): void;
18
+ export declare function appPushState(repo: string): Promise<AppPushState>;
19
+ /** For `probe`, which runs without app.db: whether the App's installation on
20
+ * the repository receives `push`. Undefined when this machine has no App
21
+ * configured, the App is not installed there, or GitHub could not be asked:
22
+ * then `probe` says nothing about commit watch. */
23
+ export declare function appPushStateWithoutDb(repo: string): Promise<"on" | "off" | undefined>;
24
+ export declare function pushVia(repo: string, review: ReviewRow): PushSource[];
25
+ export declare function watchStatus(repo: string): Promise<WatchStatus>;
@@ -0,0 +1,101 @@
1
+ /** Is commit watch on for a repository, and through what.
2
+ *
3
+ * The App watches when its installation for the repository receives the
4
+ * `push` event. That is a setting on GitHub, so it is read from
5
+ * `GET /app/installations`, and cached for a minute so a page view does not
6
+ * call GitHub every time. CI watches when a CI step has sent a push. */
7
+ import { AppJwtClient, findInstallationForRepo } from "../github/app.js";
8
+ import { readConfig, resolveAppPrivateKey } from "../config.js";
9
+ import { getRepo } from "../store/repos.js";
10
+ import { getAppDb } from "../store/app_db.js";
11
+ import { latestPushReview } from "../store/watch.js";
12
+ const CACHE_MS = 60_000;
13
+ let cache;
14
+ /** The events each installation receives, by installation id. */
15
+ async function installationEvents() {
16
+ if (cache && Date.now() - cache.at < CACHE_MS)
17
+ return cache.events;
18
+ const config = readConfig();
19
+ const pem = resolveAppPrivateKey(config);
20
+ if (!config.githubAppId || !pem)
21
+ return undefined;
22
+ try {
23
+ const installations = await new AppJwtClient(config.githubAppId, pem).listInstallations();
24
+ const events = new Map(installations.map((installation) => [
25
+ installation.id,
26
+ installation.events ?? [],
27
+ ]));
28
+ cache = { at: Date.now(), events };
29
+ return events;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ /** For tests: forget what GitHub said. */
36
+ export function clearWatchStatusCache() {
37
+ cache = undefined;
38
+ }
39
+ export async function appPushState(repo) {
40
+ const events = await installationEvents();
41
+ if (!events)
42
+ return "unknown";
43
+ const id = getRepo(repo)?.installation_id;
44
+ if (!id || !events.has(id))
45
+ return "not-installed";
46
+ return events.get(id).includes("push") ? "on" : "off";
47
+ }
48
+ /** For `probe`, which runs without app.db: whether the App's installation on
49
+ * the repository receives `push`. Undefined when this machine has no App
50
+ * configured, the App is not installed there, or GitHub could not be asked:
51
+ * then `probe` says nothing about commit watch. */
52
+ export async function appPushStateWithoutDb(repo) {
53
+ const config = readConfig();
54
+ const pem = resolveAppPrivateKey(config);
55
+ if (!config.githubAppId || !pem)
56
+ return undefined;
57
+ try {
58
+ const id = await findInstallationForRepo(config.githubAppId, pem, repo);
59
+ if (id === undefined)
60
+ return undefined;
61
+ const events = await installationEvents();
62
+ const list = events?.get(id);
63
+ if (!list)
64
+ return undefined;
65
+ return list.includes("push") ? "on" : "off";
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ function ciHasPushed(repo) {
72
+ const row = getAppDb()
73
+ .prepare(`SELECT COUNT(*) AS n FROM push_events
74
+ WHERE repo = ? AND sources LIKE '%"ci"%'`)
75
+ .get(repo);
76
+ return Number(row?.n ?? 0) > 0;
77
+ }
78
+ function viaOf(repo, review) {
79
+ const row = getAppDb()
80
+ .prepare(`SELECT sources FROM push_events WHERE repo = ? AND review_id = ?
81
+ ORDER BY created_at DESC LIMIT 1`)
82
+ .get(repo, review.id);
83
+ try {
84
+ const parsed = JSON.parse(row?.sources ?? "[]");
85
+ return parsed.filter((s) => s === "app" || s === "ci");
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ }
91
+ export function pushVia(repo, review) {
92
+ return viaOf(repo, review);
93
+ }
94
+ export async function watchStatus(repo) {
95
+ const last = latestPushReview(repo);
96
+ return {
97
+ app: await appPushState(repo),
98
+ ci: ciHasPushed(repo),
99
+ lastPush: last ? { ...last, via: viaOf(repo, last) } : undefined,
100
+ };
101
+ }
@@ -8,8 +8,14 @@ import { latestPostedReview } from "../store/reviews.js";
8
8
  import { getQueuedJob } from "../store/jobs.js";
9
9
  import { markInstallationRemoved, markInstallationSuspended, upsertInstallation, } from "../store/installations.js";
10
10
  import { readConfig } from "../config.js";
11
+ import { getWatchIssue } from "../store/watch.js";
12
+ import { canonicalRepoName } from "../util/repo_name.js";
13
+ import { isSha, isZeroSha, queuePush } from "./push_review.js";
14
+ import { WATCH_COMMENT_JOB } from "./watch_comments.js";
11
15
  import { carriesEarlierRequest, evaluatePolicy, isRequestCommand, legacyPolicy, parsePolicy, } from "./review_policy.js";
12
16
  export const REVIEW_DEBOUNCE_MS = 20_000;
17
+ /** Who may talk to commit watch on its issues: people with write access. */
18
+ const WRITE_ASSOCIATIONS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
13
19
  const PR_ACTIONS = new Set([
14
20
  "opened",
15
21
  "reopened",
@@ -195,8 +201,7 @@ export function maybeEnqueueReview(input) {
195
201
  earlier.round >= policy.maxRounds) {
196
202
  return skipped(`Round limit reached: ${earlier.round} of ${policy.maxRounds} reviews.`);
197
203
  }
198
- const last = earlier;
199
- const incremental = row.review_scope === "incremental" && Boolean(last?.head_sha);
204
+ // Round, scope and base are worked out when the job starts.
200
205
  const { id } = enqueue({
201
206
  type: "review",
202
207
  repo: input.repo,
@@ -205,9 +210,6 @@ export function maybeEnqueueReview(input) {
205
210
  debounceMs: REVIEW_DEBOUNCE_MS,
206
211
  args: {
207
212
  trigger: input.trigger,
208
- scope: incremental ? "incremental" : "whole-pr",
209
- sinceCommit: incremental ? last.head_sha : undefined,
210
- round: last ? last.round + 1 : 1,
211
213
  requestReaction: input.request?.reaction,
212
214
  },
213
215
  });
@@ -260,8 +262,9 @@ function applyInstallationRepositories(payload) {
260
262
  if (Array.isArray(added)) {
261
263
  for (const item of added) {
262
264
  const fullName = asString(asRecord(item)?.full_name);
263
- if (fullName)
264
- setInstallationId(fullName, installationId);
265
+ if (fullName) {
266
+ setInstallationId(canonicalRepoName(fullName), installationId);
267
+ }
265
268
  }
266
269
  }
267
270
  return { outcome: "ignored", reason: "repositories-added" };
@@ -272,7 +275,7 @@ function applyInstallationRepositories(payload) {
272
275
  for (const item of removed) {
273
276
  const fullName = asString(asRecord(item)?.full_name);
274
277
  if (fullName)
275
- deactivateRepo(fullName);
278
+ deactivateRepo(canonicalRepoName(fullName));
276
279
  }
277
280
  }
278
281
  return { outcome: "ignored", reason: "repositories-removed" };
@@ -511,9 +514,106 @@ function issueCommentEvent(payload, deliveryId) {
511
514
  }
512
515
  return enqueueReply(payload, deliveryId, "issue_comment", String(sourceId), repo, prNumber, body, asString(author?.login));
513
516
  }
517
+ /** Commit watch through the App: a push to the repository's default branch.
518
+ * Any other branch, a deleted branch and a tag are ignored. */
519
+ function pushEvent(payload, deliveryId) {
520
+ const repository = asRecord(payload.repository);
521
+ const repo = asString(repository?.full_name);
522
+ const ref = asString(payload.ref) ?? "";
523
+ const before = asString(payload.before) ?? "";
524
+ const after = asString(payload.after) ?? "";
525
+ const defaultBranch = asString(repository?.default_branch);
526
+ if (!repo || !defaultBranch || ref !== `refs/heads/${defaultBranch}`) {
527
+ return { outcome: "ignored", reason: "not-default-branch", repo };
528
+ }
529
+ if (asBool(payload.deleted) || !isSha(after) || isZeroSha(after)) {
530
+ return { outcome: "ignored", reason: "branch-deleted", repo };
531
+ }
532
+ if (!isSha(before))
533
+ return { outcome: "ignored", repo };
534
+ const installationId = asNumber(asRecord(payload.installation)?.id);
535
+ if (installationId !== undefined)
536
+ setInstallationId(repo, installationId);
537
+ const outcome = queuePush({
538
+ repo,
539
+ before,
540
+ after,
541
+ ref,
542
+ source: "app",
543
+ deliveryId,
544
+ });
545
+ switch (outcome.kind) {
546
+ case "enqueued":
547
+ case "attached":
548
+ return { outcome: "enqueued", repo, jobId: outcome.jobId };
549
+ case "no_changes":
550
+ return { outcome: "skipped", reason: "no-changes", repo };
551
+ case "extend":
552
+ // Only a CI diff can need a wider range, and this push has none.
553
+ return { outcome: "skipped", reason: "range-extend", repo };
554
+ case "skipped":
555
+ return { outcome: "skipped", reason: outcome.reason, repo };
556
+ }
557
+ }
558
+ /** A comment on an issue commit watch opened. Only someone with write access
559
+ * is listened to, and the comment job decides whether it was meant for us. */
560
+ function watchIssueCommentEvent(payload, deliveryId) {
561
+ const issue = asRecord(payload.issue);
562
+ const comment = asRecord(payload.comment);
563
+ const repo = asString(asRecord(payload.repository)?.full_name);
564
+ const number = asNumber(issue?.number);
565
+ const commentId = comment?.id;
566
+ if (asString(payload.action) !== "created" ||
567
+ !repo ||
568
+ number === undefined ||
569
+ (typeof commentId !== "number" && typeof commentId !== "string")) {
570
+ return { outcome: "ignored", repo };
571
+ }
572
+ if (!getWatchIssue(repo, number)) {
573
+ return { outcome: "ignored", reason: "not-a-watch-issue", repo };
574
+ }
575
+ const author = asRecord(comment?.user);
576
+ if (isBot(author)) {
577
+ return { outcome: "skipped", reason: "own-comment", repo };
578
+ }
579
+ const association = asString(comment?.author_association) ?? "NONE";
580
+ if (!WRITE_ASSOCIATIONS.has(association)) {
581
+ return {
582
+ outcome: "skipped",
583
+ reason: `no-write-access: ${association}`,
584
+ repo,
585
+ };
586
+ }
587
+ const row = getRepo(repo);
588
+ if (!row || row.active !== 1) {
589
+ return { outcome: "skipped", reason: "repo-not-active", repo };
590
+ }
591
+ const installationId = asNumber(asRecord(payload.installation)?.id);
592
+ if (installationId !== undefined)
593
+ setInstallationId(repo, installationId);
594
+ const { id } = enqueue({
595
+ type: WATCH_COMMENT_JOB,
596
+ repo,
597
+ deliveryId,
598
+ queueKey: `watch-comment:${repo}:${String(commentId)}`,
599
+ args: {
600
+ issueNumber: number,
601
+ commentId: String(commentId),
602
+ author: asString(author?.login) ?? null,
603
+ body: (asString(comment?.body) ?? "").slice(0, 20_000),
604
+ },
605
+ });
606
+ return { outcome: "enqueued", repo, jobId: id };
607
+ }
514
608
  export function dispatchGithubEvent(event, payload, deliveryId, maxDiffLines) {
515
609
  if (event === "installation")
516
610
  return applyInstallation(payload);
611
+ if (event === "push")
612
+ return pushEvent(payload, deliveryId);
613
+ if (event === "issue_comment" &&
614
+ !asRecord(asRecord(payload.issue)?.pull_request)) {
615
+ return watchIssueCommentEvent(payload, deliveryId);
616
+ }
517
617
  if (event === "installation_repositories") {
518
618
  return applyInstallationRepositories(payload);
519
619
  }