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
@@ -47,9 +47,16 @@ export interface ReviewMetadata {
47
47
  durationMs: number;
48
48
  }
49
49
  export declare function formatDuration(ms: number): string;
50
- /** Short summary on the review itself. Findings that map to the diff go
51
- * inline. Leftovers are listed here as one line each, not as a CLI dump. */
52
- export declare function reviewBody(findings: ParsedFinding[], metadata: ReviewMetadata, _inlineCount?: number): string;
50
+ /** A finding an earlier round reported that this round still finds, with the
51
+ * commit that first found it when known. */
52
+ export type StillOpenFinding = {
53
+ finding: ParsedFinding;
54
+ since?: string;
55
+ };
56
+ /** Short summary on the review itself, one line per open finding, split
57
+ * into what this round found and what earlier rounds found that still
58
+ * holds, so a repeat never reads as a new problem. */
59
+ export declare function reviewBody(findings: ParsedFinding[], metadata: ReviewMetadata, stillOpen?: StillOpenFinding[]): string;
53
60
  /** A review job's options: the config, with the job's pinned model (a
54
61
  * "Retry with the same model") over the configured one. */
55
62
  export declare function reviewOptionsForJob(repo: string, prNumber: number, args: {
@@ -71,3 +78,13 @@ export declare function enqueueManualReview(repo: string, prNumber: number, pin?
71
78
  id: string;
72
79
  debounced: boolean;
73
80
  };
81
+ /** The round, scope and base of the next review after `last`. A job queued
82
+ * without them works them out when it starts. */
83
+ export declare function roundArgs(repo: string, last: {
84
+ head_sha: string | null;
85
+ round: number;
86
+ } | undefined): {
87
+ scope: string;
88
+ sinceCommit?: string;
89
+ round: number;
90
+ };
@@ -17,12 +17,13 @@ import { matchRepeat } from "../pr/rounds.js";
17
17
  import { readConfig, resolveAppPrivateKey, resolvedAiToken, } from "../config.js";
18
18
  import { outsideCode, redact } from "../util/redact.js";
19
19
  import { getRepo, setInstallationId } from "../store/repos.js";
20
- import { findNoteCommentId, getReviewByJobId, insertReview, latestPostedReview, setReviewScope, setReviewStatus, } from "../store/reviews.js";
20
+ import { findNoteCommentId, getReview, getReviewByJobId, insertReview, latestPostedReview, setReviewScope, setReviewStatus, } from "../store/reviews.js";
21
21
  import { insertFinding, listCarryableFindingsForReview, listFindingsForPr, listFindingsForReview, setFindingPosted, } from "../store/findings.js";
22
22
  import { getOrCreatePrSubject, getSubjectRevision, parseRevisionFiles, parseVisiblePaths, saveSubjectRevision, } from "../store/subjects.js";
23
23
  import { enqueue, registerHandler } from "./jobs.js";
24
24
  import { requestedReviewBlocked } from "./webhook.js";
25
25
  import { getEnv } from "../util/runtime.js";
26
+ import { hasWriteAccess } from "../github/write_access.js";
26
27
  const ACCESS_DENIED_BODY = "The App does not have access to review this pull request.";
27
28
  /** The first words of the single note a failed review leaves on the pull
28
29
  * request. The note names no provider error and no retry command: both live
@@ -177,19 +178,32 @@ function metadataBlock({ jobId, model, durationMs }) {
177
178
  `- Duration: ${formatDuration(durationMs)}\n` +
178
179
  `</details>`);
179
180
  }
180
- /** Short summary on the review itself. Findings that map to the diff go
181
- * inline. Leftovers are listed here as one line each, not as a CLI dump. */
182
- export function reviewBody(findings, metadata, _inlineCount = 0) {
183
- if (findings.length === 0) {
181
+ function summaryLine(finding, since) {
182
+ const title = humanCopy(finding.heading || finding.path);
183
+ const summary = humanCopy(finding.summary ??
184
+ finding.excerpt.split(/\r?\n/).find((line) => line.trim()) ??
185
+ "");
186
+ const first = since ? ` (first found in ${since.slice(0, 7)})` : "";
187
+ return `- ${title}${summary ? `: ${summary}` : ""}${first}`;
188
+ }
189
+ /** Short summary on the review itself, one line per open finding, split
190
+ * into what this round found and what earlier rounds found that still
191
+ * holds, so a repeat never reads as a new problem. */
192
+ export function reviewBody(findings, metadata, stillOpen = []) {
193
+ if (findings.length === 0 && stillOpen.length === 0) {
184
194
  return `No actionable findings.${metadataBlock(metadata)}`;
185
195
  }
186
- const lines = ["Review summary", ""];
187
- for (const finding of findings) {
188
- const title = humanCopy(finding.heading || finding.path);
189
- const summary = humanCopy(finding.summary ??
190
- finding.excerpt.split(/\r?\n/).find((line) => line.trim()) ??
191
- "");
192
- lines.push(`- ${title}${summary ? `: ${summary}` : ""}`);
196
+ const lines = ["Review summary"];
197
+ if (findings.length) {
198
+ lines.push("", `New (${findings.length})`);
199
+ for (const finding of findings)
200
+ lines.push(summaryLine(finding));
201
+ }
202
+ if (stillOpen.length) {
203
+ lines.push("", `Still open (${stillOpen.length})`);
204
+ for (const { finding, since } of stillOpen) {
205
+ lines.push(summaryLine(finding, since));
206
+ }
193
207
  }
194
208
  return lines.join("\n") + metadataBlock(metadata);
195
209
  }
@@ -237,6 +251,49 @@ async function postedCommentBodies(client, job, log) {
237
251
  return new Map();
238
252
  }
239
253
  }
254
+ /** What people with write access replied on each finding's inline thread,
255
+ * oldest first, keyed by finding id. The next round weighs them when it
256
+ * decides whether the finding still holds. */
257
+ async function findingReplies(client, job, rows, log) {
258
+ const byThread = new Map();
259
+ for (const row of rows) {
260
+ for (const id of [row.posted_comment_id, row.thread_comment_id]) {
261
+ if (id)
262
+ byThread.set(id, row.id);
263
+ }
264
+ }
265
+ const replies = new Map();
266
+ if (byThread.size === 0)
267
+ return replies;
268
+ let listed;
269
+ try {
270
+ listed = await client.pages(`repos/${job.repo}/pulls/${job.pr_number}/comments`);
271
+ }
272
+ catch (error) {
273
+ log("info", `could not read the review threads: ${redact(String(error))}`);
274
+ return replies;
275
+ }
276
+ const access = new Map();
277
+ const sorted = [...listed].sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")));
278
+ for (const comment of sorted) {
279
+ const findingId = byThread.get(String(comment.in_reply_to_id ?? ""));
280
+ const user = comment.user;
281
+ const login = String(user?.login ?? "");
282
+ if (!findingId || !login)
283
+ continue;
284
+ if (user?.type === "Bot" || login.endsWith("[bot]"))
285
+ continue;
286
+ if (!access.has(login)) {
287
+ access.set(login, hasWriteAccess(client, job.repo, login));
288
+ }
289
+ if (!(await access.get(login)))
290
+ continue;
291
+ const list = replies.get(findingId) ?? [];
292
+ list.push(String(comment.body ?? ""));
293
+ replies.set(findingId, list);
294
+ }
295
+ return replies;
296
+ }
240
297
  /** A review job's options: the config, with the job's pinned model (a
241
298
  * "Retry with the same model") over the configured one. */
242
299
  export function reviewOptionsForJob(repo, prNumber, args) {
@@ -402,7 +459,7 @@ async function publish(client, job, reviewId, headSha, files, log, metadata, mod
402
459
  });
403
460
  const freshRows = stored.filter((row) => !repeats.includes(row) && (row.state === "new" || row.thread_comment_id));
404
461
  const fresh = freshRows.map(rowFinding);
405
- const { inline, leftover } = splitInline(fresh, files);
462
+ const { inline } = splitInline(fresh, files);
406
463
  const commentByRow = new Map();
407
464
  for (const { finding, anchor, suggestion } of inline) {
408
465
  const row = freshRows.find((item) => item.path === finding.path &&
@@ -415,25 +472,20 @@ async function publish(client, job, reviewId, headSha, files, log, metadata, mod
415
472
  });
416
473
  }
417
474
  }
418
- const freshSummaryKeys = new Set([...leftover, ...inline.map(({ finding }) => finding)].map((finding) => `${finding.path}\0${finding.from}\0${finding.to}`));
419
- const summaryFindings = [
420
- ...leftover,
421
- ...inline.map(({ finding }) => finding),
422
- ...stored
423
- .filter((row) => row.state !== "closed")
424
- .filter((row) => {
425
- const key = `${row.path ?? ""}\0${row.line_from ?? 0}\0${row.line_to ?? row.line_from ?? 0}`;
426
- return !freshSummaryKeys.has(key);
427
- })
428
- .map((row) => ({
429
- path: row.path ?? "",
430
- from: row.line_from ?? 0,
431
- to: row.line_to ?? row.line_from ?? 0,
432
- heading: row.title,
433
- excerpt: row.body_md,
434
- })),
435
- ];
436
- const body = reviewBody(summaryFindings, metadata, inline.length + repeats.length);
475
+ // The summary lists every open finding once, by what this round made of
476
+ // it: found now, or found by an earlier round and still there.
477
+ const summaryFindings = stored
478
+ .filter((row) => row.state === "new")
479
+ .map(rowFinding);
480
+ const stillOpen = stored
481
+ .filter((row) => row.state === "open")
482
+ .map((row) => ({
483
+ finding: rowFinding(row),
484
+ since: row.first_seen_review_id
485
+ ? (getReview(row.first_seen_review_id)?.head_sha ?? undefined)
486
+ : undefined,
487
+ }));
488
+ const body = reviewBody(summaryFindings, metadata, stillOpen);
437
489
  const comments = inline.map(({ finding, anchor, suggestion }) => ({
438
490
  path: finding.path,
439
491
  body: inlineCommentBody(finding, suggestion),
@@ -489,7 +541,7 @@ async function publish(client, job, reviewId, headSha, files, log, metadata, mod
489
541
  if (error instanceof GitHubHttpError && error.status === 422) {
490
542
  log("info", "inline comments rejected, falling back to an issue comment");
491
543
  const posted = await post(client, `repos/${job.repo}/issues/${job.pr_number}/comments`, {
492
- body: reviewBody(summaryFindings, metadata),
544
+ body: reviewBody(summaryFindings, metadata, stillOpen),
493
545
  });
494
546
  setReviewStatus(reviewId, "posted", {
495
547
  posted_review_id: String(posted.id ?? ""),
@@ -604,6 +656,21 @@ async function runReviewJobCore(job, log, client, ai) {
604
656
  }
605
657
  const headSha = String(pr.head?.sha ?? "");
606
658
  const mergeBase = String(pr.base?.sha ?? "");
659
+ if (!existing) {
660
+ const last = latestPostedReview(job.repo, job.pr_number);
661
+ // A review or comment that arrived while a review of this head was
662
+ // running queued this job. That review has posted by now.
663
+ if ((args.trigger === "review" || args.trigger === "review-comment") &&
664
+ last?.head_sha === headSha) {
665
+ log("info", "this head was already reviewed, nothing new to review");
666
+ return;
667
+ }
668
+ // Round and base come from the review that posted last, read now rather
669
+ // than when the job was queued: a review may have posted in between.
670
+ if (args.round === undefined) {
671
+ Object.assign(args, roundArgs(job.repo, last));
672
+ }
673
+ }
607
674
  let scope = args.scope === "incremental" ? "incremental" : "whole-pr";
608
675
  if (scope === "incremental" && !args.sinceCommit) {
609
676
  scope = "whole-pr";
@@ -700,6 +767,7 @@ async function runReviewJobCore(job, log, client, ai) {
700
767
  const { unchanged } = incrementalDiffPaths(revision, prevFiles);
701
768
  extras.unchangedPaths = scope === "incremental" ? unchanged : undefined;
702
769
  const storedRows = listCarryableFindingsForReview(subjectRevision.review_id);
770
+ const replies = await findingReplies(github, job, storedRows, log);
703
771
  carryPrevious = {
704
772
  files: prevFiles,
705
773
  visiblePaths: parseVisiblePaths(subjectRevision),
@@ -713,6 +781,7 @@ async function runReviewJobCore(job, log, client, ai) {
713
781
  anchorText: row.anchor_text,
714
782
  severity: row.severity,
715
783
  firstSeenReviewId: row.first_seen_review_id ?? subjectRevision.review_id,
784
+ replies: replies.get(row.id),
716
785
  })),
717
786
  guideBuiltAt: subjectRevision.guide_built_at,
718
787
  };
@@ -843,19 +912,23 @@ export function registerReviewJobHandler() {
843
912
  * model" asks; without it the job resolves the model from config when it
844
913
  * runs. */
845
914
  export function enqueueManualReview(repo, prNumber, pin = {}) {
846
- const last = latestPostedReview(repo, prNumber);
847
- const row = getRepo(repo);
848
- const incremental = row?.review_scope === "incremental" && Boolean(last?.head_sha);
849
915
  return enqueue({
850
916
  type: "review",
851
917
  repo,
852
918
  prNumber,
853
919
  args: {
854
920
  trigger: "manual",
855
- scope: incremental ? "incremental" : "whole-pr",
856
- sinceCommit: incremental ? last.head_sha : undefined,
857
- round: last ? last.round + 1 : 1,
858
921
  ...(pin.model ? { model: pin.model } : {}),
859
922
  },
860
923
  });
861
924
  }
925
+ /** The round, scope and base of the next review after `last`. A job queued
926
+ * without them works them out when it starts. */
927
+ export function roundArgs(repo, last) {
928
+ const incremental = getRepo(repo)?.review_scope === "incremental" && Boolean(last?.head_sha);
929
+ return {
930
+ scope: incremental ? "incremental" : "whole-pr",
931
+ sinceCommit: incremental ? last.head_sha : undefined,
932
+ round: last ? last.round + 1 : 1,
933
+ };
934
+ }
@@ -21,6 +21,7 @@ import { closeAppDb, isAppDbOpen, openAppDb } from "../store/app_db.js";
21
21
  import { getRepo, markKnowledgeBuilt, registerCliRepo, } from "../store/repos.js";
22
22
  import { nowIso } from "../util/time.js";
23
23
  import { mkdir, readTextFile, remove } from "../util/runtime.js";
24
+ import { applyWatchNotes, withMaintainerNotes } from "./watch_notes.js";
24
25
  import { addResponseCost, emptyTally } from "../util/cost.js";
25
26
  import { costLabel } from "../util/run_summary.js";
26
27
  import { formatError } from "../cli/error.js";
@@ -114,6 +115,21 @@ async function writeReviewDocuments(repo, documents, signalCount) {
114
115
  await remove(`${directory}/PR_REVIEW_DETAILED_GUIDE.md`).catch(() => { });
115
116
  }
116
117
  }
118
+ /** Puts the commit watch maintainer notes at the end of the detailed guide,
119
+ * which every review reads. Called after the guides are written, so a guide
120
+ * the AI just rebuilt keeps them. */
121
+ async function writeMaintainerNotes(repo, lines) {
122
+ const path = `${reposDir()}/${repo}/PR_REVIEW_DETAILED_GUIDE.md`;
123
+ let current = "";
124
+ try {
125
+ current = await readTextFile(path);
126
+ }
127
+ catch {
128
+ // No detailed guide yet: the notes start one.
129
+ }
130
+ const { writeTextFileAtomic } = await import("../util/atomic.js");
131
+ await writeTextFileAtomic(path, withMaintainerNotes(current, lines));
132
+ }
117
133
  /** Writes the codebase-description sections (layout/style/tests/devloop) to
118
134
  * their own file, so `review` can check a pull request against how this
119
135
  * repository's code actually looks, not just the review-bar checklist. Every
@@ -242,6 +258,8 @@ async function initOrRemake(options) {
242
258
  }
243
259
  let result = await timed("assemble skill", options.logTime, () => assembleSkill(options.repo, facts, previousMarkdown, previous?.sectionHashes ?? {}, overrides));
244
260
  result.markdown = addReviewLink(result.markdown, reviewDocuments);
261
+ // What maintainers said on commit watch issues since the last sync.
262
+ const noteLines = await applyWatchNotes(options.repo, lowAi, (response) => usage("watch_note", response));
245
263
  const validation = await timed("validate skill", options.logTime, () => validateSkill(result.markdown, source));
246
264
  // There is no deterministic fallback to reassemble from: a skill the AI could
247
265
  // not write correctly is reported rather than rebuilt from facts.
@@ -262,6 +280,9 @@ async function initOrRemake(options) {
262
280
  await writeTextFileAtomic(path, result.markdown);
263
281
  await writeCodebaseDocument(options.repo, overrides);
264
282
  await writeReviewDocuments(options.repo, reviewDocuments, reviewSignalCount(facts));
283
+ if (noteLines.length > 0) {
284
+ await writeMaintainerNotes(options.repo, noteLines);
285
+ }
265
286
  const head = source.commits[0];
266
287
  const baseSha = head?.sha ? String(head.sha) : new Date().toISOString();
267
288
  // A CLI init has no app.db row for the repository yet; without one the
@@ -0,0 +1,10 @@
1
+ export declare const WATCH_COMMENT_JOB = "watch_comment";
2
+ export type CommentKind = "question" | "ignore" | "info";
3
+ export type Classification = {
4
+ forUs: boolean;
5
+ kind: CommentKind | "other";
6
+ };
7
+ /** Reads the classifier's answer. Anything unreadable is "not for us", so a
8
+ * broken answer never makes co-maintainer speak. */
9
+ export declare function parseClassification(text: string): Classification;
10
+ export declare function registerWatchCommentHandler(): void;
@@ -0,0 +1,166 @@
1
+ /** Comments on commit watch issues.
2
+ *
3
+ * The webhook already checked that the issue is ours and that the author has
4
+ * write access. The low model then decides whether the comment is meant for
5
+ * co-maintainer at all ("@asd can you take a look" is not) and whether it is
6
+ * a question, a request to ignore the finding, or information. A question
7
+ * gets an answer from the high model, in the comment's language. Ignore and
8
+ * information get a short "noted" and wait for the next sync, which puts the
9
+ * note in the detailed review guide and, for ignore, stops reporting the
10
+ * finding. */
11
+ import { createAiProvider } from "../ai/provider.js";
12
+ import { FakeAiProvider } from "../ai/fake.js";
13
+ import { completeWithMermaidTools } from "../ai/mermaid_loop.js";
14
+ import { loadGuides } from "../review/guides.js";
15
+ import { getEnv } from "../util/runtime.js";
16
+ import { hasWriteAccess } from "../github/write_access.js";
17
+ import { getWatchIssue, insertWatchNote } from "../store/watch.js";
18
+ import { registerHandler } from "./jobs.js";
19
+ import { recordAiCost } from "./setup.js";
20
+ import { aiFor, clientFor, humanCopy, resolveInstallationId, reviewOptions, } from "./review.js";
21
+ import { commentOnIssue, excerpt, fileAt, NOTED_REPLY, } from "./watch_issues.js";
22
+ export const WATCH_COMMENT_JOB = "watch_comment";
23
+ function replyMarker(commentId) {
24
+ return `<!-- co-maintainer:watch-reply ${commentId} -->`;
25
+ }
26
+ function lowAiFor(options) {
27
+ if (getEnv("CM_FAKE_AI") === "1")
28
+ return new FakeAiProvider();
29
+ const provider = createAiProvider(options, options.lowModel ?? "");
30
+ if (!provider)
31
+ throw new Error("commit watch comments need an AI provider");
32
+ return provider;
33
+ }
34
+ /** Reads the classifier's answer. Anything unreadable is "not for us", so a
35
+ * broken answer never makes co-maintainer speak. */
36
+ export function parseClassification(text) {
37
+ const match = /\{[\s\S]*\}/.exec(text);
38
+ if (!match)
39
+ return { forUs: false, kind: "other" };
40
+ try {
41
+ const value = JSON.parse(match[0]);
42
+ const kind = value.kind === "question" ||
43
+ value.kind === "ignore" ||
44
+ value.kind === "info"
45
+ ? value.kind
46
+ : "other";
47
+ return { forUs: value.forUs === true, kind };
48
+ }
49
+ catch {
50
+ return { forUs: false, kind: "other" };
51
+ }
52
+ }
53
+ function classifyPrompt(issueTitle, issueBody, comment) {
54
+ return `An issue was opened by co-maintainer, an automated code reviewer, for a
55
+ problem its review found on the default branch. A maintainer commented on it.
56
+
57
+ Decide two things and answer with one JSON object and nothing else:
58
+ {"forUs": true|false, "kind": "question"|"ignore"|"info"|"other"}
59
+
60
+ forUs: true only when the comment speaks to co-maintainer (or to the bot, or
61
+ to whoever opened the issue). A comment that addresses another person, for
62
+ example "@asd can you take a look", is false.
63
+ kind:
64
+ - "question": asks co-maintainer something about the problem.
65
+ - "ignore": says the finding is not a problem, is intended, or should be
66
+ ignored from now on.
67
+ - "info": tells co-maintainer something it should know for later reviews.
68
+ - "other": anything else.
69
+
70
+ ISSUE TITLE: ${issueTitle}
71
+ ISSUE:
72
+ ${issueBody.slice(0, 4000)}
73
+
74
+ COMMENT:
75
+ ${comment.slice(0, 6000)}`;
76
+ }
77
+ async function alreadyAnswered(client, repo, issueNumber, commentId) {
78
+ try {
79
+ const comments = await client.pages(`repos/${repo}/issues/${issueNumber}/comments`, 300);
80
+ const marker = replyMarker(commentId);
81
+ return comments.some((comment) => String(comment.body ?? "").includes(marker));
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ }
87
+ async function runWatchComment(job, log) {
88
+ const args = JSON.parse(job.args);
89
+ const issue = getWatchIssue(job.repo, args.issueNumber);
90
+ if (!issue) {
91
+ log("info", "the issue is no longer tracked");
92
+ return;
93
+ }
94
+ const installationId = await resolveInstallationId(job.repo);
95
+ if (installationId === undefined) {
96
+ throw new Error("no GitHub App installation covers this repository");
97
+ }
98
+ const client = clientFor(installationId);
99
+ if (!(await hasWriteAccess(client, job.repo, args.author))) {
100
+ log("info", `${args.author ?? "the commenter"} has no write access`);
101
+ return;
102
+ }
103
+ if (await alreadyAnswered(client, job.repo, args.issueNumber, args.commentId)) {
104
+ log("info", "this comment was already answered");
105
+ return;
106
+ }
107
+ const options = reviewOptions(job.repo, 0);
108
+ const usage = async (response) => {
109
+ await recordAiCost(job.repo, "watch_comment", response);
110
+ };
111
+ const classified = await lowAiFor(options).complete({
112
+ job: "watch_comment_classify",
113
+ prompt: classifyPrompt(issue.title, issue.body_md, args.body),
114
+ maxTokens: 200,
115
+ });
116
+ await usage(classified);
117
+ const decision = parseClassification(classified.text);
118
+ log("info", `comment classified: forUs=${decision.forUs} kind=${decision.kind}`);
119
+ if (!decision.forUs || decision.kind === "other")
120
+ return;
121
+ const marker = replyMarker(args.commentId);
122
+ if (decision.kind === "ignore" || decision.kind === "info") {
123
+ insertWatchNote({
124
+ repo: job.repo,
125
+ issueNumber: args.issueNumber,
126
+ commentId: args.commentId,
127
+ author: args.author,
128
+ kind: decision.kind,
129
+ body: args.body,
130
+ });
131
+ await commentOnIssue(client, job.repo, args.issueNumber, `${NOTED_REPLY}\n\n${marker}`);
132
+ return;
133
+ }
134
+ const guides = await loadGuides(job.repo);
135
+ const content = issue.path
136
+ ? await fileAt(client, job.repo, issue.path, "")
137
+ : undefined;
138
+ const code = content && issue.path
139
+ ? `${issue.path}:\n${excerpt(content, issue.line_from ?? 1, issue.line_to ?? issue.line_from ?? 1)}`
140
+ : "The file is not available.";
141
+ const answer = await completeWithMermaidTools(aiFor(options), {
142
+ job: "watch_comment_answer",
143
+ reasoningEffort: "high",
144
+ maxTokens: 6000,
145
+ system: `You are co-maintainer, the code reviewer that opened this issue. Answer the maintainer's question about the problem in plain prose. Write the answer in the same language as the question. Do not use semicolons.
146
+
147
+ REVIEW GUIDE:
148
+ ${(guides.shortGuide || guides.skill || "").slice(0, 20_000)}`,
149
+ prompt: `ISSUE #${args.issueNumber}: ${issue.title}
150
+ ${issue.body_md.slice(0, 6000)}
151
+
152
+ CURRENT CODE:
153
+ ${code.slice(0, 20_000)}
154
+
155
+ QUESTION from ${args.author ?? "a maintainer"}:
156
+ ${args.body.slice(0, 6000)}`,
157
+ }, 5);
158
+ await usage(answer);
159
+ const text = humanCopy(answer.text).trim();
160
+ if (!text)
161
+ throw new Error("the AI returned an empty answer");
162
+ await commentOnIssue(client, job.repo, args.issueNumber, `${text}\n\n${marker}`);
163
+ }
164
+ export function registerWatchCommentHandler() {
165
+ registerHandler(WATCH_COMMENT_JOB, { run: runWatchComment });
166
+ }
@@ -0,0 +1,70 @@
1
+ import type { GitHubClient } from "../types.ts";
2
+ export declare const ISSUE_LABEL = "co-maintainer";
3
+ export declare const ISSUE_SEVERITIES: Set<string>;
4
+ export declare const CLOSE_DENIED_COMMENT = "I tried to close this issue, but I do not have permission to close issues in this repository.";
5
+ export declare const NOTED_REPLY = "Noted, I will take this into account on the next sync.";
6
+ export declare function shortSha(sha: string): string;
7
+ /** `abc1234..def5678`, the range a push review covered. */
8
+ export declare function pushRange(before: string, after: string): string;
9
+ export declare function findingMarker(id: string): string;
10
+ /** The finding in a few words, for the issue title and for later prompts:
11
+ * the body's first line, which the review writes as one sentence naming the
12
+ * defect. The heading (`[P1 · blocking] \`path\`: \`symbol\``) is the
13
+ * fallback. */
14
+ export declare function findingSummary(heading: string, body: string): string;
15
+ export declare function issueTitle(severity: string, summary: string): string;
16
+ export declare function permalink(repo: string, sha: string, path: string, from: number | null, to: number | null): string;
17
+ export declare function issueBody(input: {
18
+ id: string;
19
+ body: string;
20
+ repo: string;
21
+ after: string;
22
+ before: string;
23
+ branch: string;
24
+ path: string | null;
25
+ lineFrom: number | null;
26
+ lineTo: number | null;
27
+ }): string;
28
+ /** `commit` changed the finding's lines, `after` is the push. When they are
29
+ * the same commit it is written once. */
30
+ export declare function stillFoundComment(commit: string, after: string, range: string): string;
31
+ export declare function fixedComment(commit: string, range: string): string;
32
+ export declare function closedStillFoundComment(range: string): string;
33
+ /** Creates each label the issue needs. A label that already exists answers
34
+ * 422, which is fine. */
35
+ export declare function ensureLabels(client: GitHubClient, repo: string, names: string[]): Promise<void>;
36
+ export declare function openIssue(client: GitHubClient, repo: string, input: {
37
+ title: string;
38
+ body: string;
39
+ severity: string;
40
+ }): Promise<number>;
41
+ export declare function commentOnIssue(client: GitHubClient, repo: string, issueNumber: number, body: string): Promise<string>;
42
+ /** Closes the issue, or leaves the comment that says it could not. Returns
43
+ * whether it closed. */
44
+ export declare function closeIssue(client: GitHubClient, repo: string, issueNumber: number): Promise<boolean>;
45
+ export type IssueState = {
46
+ open: boolean;
47
+ closedByBot: boolean;
48
+ };
49
+ /** Whether the issue is open on GitHub, and when closed whether a bot (this
50
+ * App) closed it. */
51
+ export declare function readIssueState(client: GitHubClient, repo: string, issueNumber: number): Promise<IssueState | undefined>;
52
+ /** A file's text at a commit (the default branch when `sha` is empty), or
53
+ * undefined when it is gone or unreadable. */
54
+ export declare function fileAt(client: GitHubClient, repo: string, path: string, sha: string): Promise<string | undefined>;
55
+ /** The newest commit at or before `sha` that touched `path`, which inside a
56
+ * push that changed the file is the commit that changed it. */
57
+ export declare function lastCommitFor(client: GitHubClient, repo: string, path: string, sha: string): Promise<string | undefined>;
58
+ /** Where `anchor` sits in `content`, the closest match to `oldFrom` when it
59
+ * appears more than once. Blank lines are skipped on both sides, the same
60
+ * way `normalizeAnchor` drops them. */
61
+ export declare function locateAnchor(content: string, anchor: string | null, oldFrom: number): {
62
+ from: number;
63
+ to: number;
64
+ } | undefined;
65
+ /** The new-file line numbers a patch adds or changes. */
66
+ export declare function changedLines(patch: string): Set<number>;
67
+ /** The finding's code with line numbers and a few lines around it, for the
68
+ * known-issue check. */
69
+ export declare function excerpt(content: string, from: number, to: number): string;
70
+ export declare function samePath(a: string | null, b: string | null): boolean;