@mergelight/cli 0.1.14 → 0.1.16

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.
@@ -1,23 +1,26 @@
1
+ import { RESOLVED_ONLY } from "../prompt.js";
1
2
  import { GitHub } from "./api.js";
2
3
  import { commentableLines, place } from "./diff-lines.js";
3
- import { closedBody, readClosed, reopenedBody, resolvedByPeople, threadAction, threadFinding } from "./closed.js";
4
+ import { answeredRemembered, closedBody, patchTouches, readClosed, REMEMBERED_MARKER, reopenedBody, resolvedByPeople, resolverReplies, threadAction, threadFinding } from "./closed.js";
4
5
  import { failedSummaryBody, FINDING_MARKER_RE, headline, inlineBody, isFailedSummary, isPendingSummary, LIGHT, pendingSummaryBody, SUMMARY_MARKER, summaryBody } from "./markdown.js";
5
- import { readMarks, trustedComment, writeAccess } from "./handled.js";
6
+ import { askWriteAccess, MAX_NOTE, readMarks, trustedComment, writeAccess } from "./handled.js";
7
+ import { withoutHidden } from "../skills.js";
6
8
  import { decodeState, nextState } from "./state.js";
7
9
  import { newerVersion } from "../update.js";
8
10
  export { trustedComment } from "./handled.js";
9
11
  export const CHECK_NAME = "Mergelight";
10
12
  /**
11
- * How each merge light shows up as a GitHub check. Yellow is neutral, which
12
- * GitHub counts as passing: a solo developer can't approve their own PR, so
13
- * yellow must not wait for an approval unless a team asks for that. Then it's
14
- * action_required, which doesn't pass until someone approves (see approveCheck).
13
+ * How each merge light shows up as a GitHub check. Red and yellow are neutral, which GitHub counts as
14
+ * passing and shows without a red cross: a review is a judgment, not a failed build, and the title
15
+ * still says what it found. A team that wants the check to hold merges sets yellowBlocks: then yellow
16
+ * is action_required, which doesn't pass until someone approves (see approveCheck), and red fails
17
+ * until the code changes.
15
18
  */
16
19
  export function checkConclusion(light, yellowBlocks = false) {
17
20
  if (light === "green")
18
21
  return "success";
19
22
  if (light === "red")
20
- return "failure";
23
+ return yellowBlocks ? "failure" : "neutral";
21
24
  return yellowBlocks ? "action_required" : "neutral";
22
25
  }
23
26
  /**
@@ -38,30 +41,147 @@ export async function readPrReviewState(api, number) {
38
41
  const issueComments = await api.list(`issues/${number}/comments`);
39
42
  const reviewComments = await api.list(`pulls/${number}/comments`);
40
43
  const summary = await ownSummary(issueComments, () => api.viewer());
41
- const marks = await readMarks([...issueComments, ...reviewComments], writeAccess(api));
44
+ const marks = await readMarks([...issueComments, ...reviewComments], askWriteAccess(api));
42
45
  return { summary, state: decodeState(summary?.body), marks, reviewComments };
43
46
  }
44
47
  const MAX_PREVIOUS = 40;
45
- /** What earlier rounds found on this PR, latest first, for the verifier to check again. */
46
- export async function previousFindings(api, number) {
47
- const { state, marks } = await readPrReviewState(api, number);
48
- const resolved = await resolvedByPeople(await reviewThreads(api, number).catch(() => []), writeAccess(api));
48
+ /**
49
+ * Whether the code at a finding is as the latest review saw it. Asked of GitHub once, for the whole
50
+ * change since then. Anything it can't tell counts as changed.
51
+ */
52
+ function unchangedSince(api, since, headSha) {
53
+ if (!since || !headSha)
54
+ return async () => false;
55
+ if (since === headSha)
56
+ return async () => true;
57
+ let files;
58
+ return async (f) => {
59
+ files ??= api
60
+ .get(`compare/${since}...${headSha}`)
61
+ .then((r) => {
62
+ // Only a head that builds on the reviewed commit gives line numbers that match the finding's. After a
63
+ // force-push the diff starts somewhere else. GitHub also lists at most 300 files: past that, a file
64
+ // that isn't listed may still have changed.
65
+ if (r.status !== "ahead" || !r.files || r.files.length >= 300)
66
+ return null;
67
+ const out = new Map();
68
+ for (const file of r.files) {
69
+ out.set(file.filename, file.patch ?? null);
70
+ if (file.previous_filename)
71
+ out.set(file.previous_filename, null);
72
+ }
73
+ return out;
74
+ })
75
+ .catch(() => null);
76
+ const changed = await files;
77
+ if (!changed)
78
+ return false;
79
+ if (!changed.has(f.file))
80
+ return true;
81
+ const patch = changed.get(f.file);
82
+ return patch ? !patchTouches(patch, f.line, f.end_line ?? f.line) : false;
83
+ };
84
+ }
85
+ /**
86
+ * What earlier rounds found on this PR, latest first, for the verifier to check again.
87
+ * headSha: the commit this review is about, to tell a reason from a fix.
88
+ */
89
+ export async function previousFindings(api, number, headSha) {
90
+ const { summary, state, marks } = await readPrReviewState(api, number);
91
+ const threads = await reviewThreads(api, number).catch(() => []);
92
+ const resolved = await resolvedByPeople(threads, writeAccess(api));
93
+ // Mergelight's own login is the one its summary comment carries.
94
+ const replies = resolverReplies(threads, resolved, summary?.user?.login ?? undefined);
95
+ const latest = state?.rounds.at(-1);
96
+ const waiting = new Map((state?.remember ?? []).map((r) => [r.id, r]));
97
+ const unchanged = unchangedSince(api, latest?.sha, headSha);
49
98
  // A decision not to fix must reach the verifier however long the list gets, or the problem comes back as new.
50
99
  const order = (f) => (marks.get(f.id)?.as === "wont_fix" || resolved.has(f.id) ? 0 : f.status === "gone" ? 2 : 1);
51
- return (state?.findings ?? [])
52
- .sort((a, b) => order(a) - order(b))
53
- .slice(0, MAX_PREVIOUS)
54
- .map(({ id, title, file, line, end_line, how }) => {
100
+ const kept = (state?.findings ?? []).sort((a, b) => order(a) - order(b)).slice(0, MAX_PREVIOUS);
101
+ return Promise.all(kept.map(async (f) => {
102
+ const { id, title, file, line, end_line, how } = f;
55
103
  const mark = marks.get(id);
56
104
  const by = resolved.get(id);
105
+ const reply = replies.get(id);
106
+ // What the resolver wrote reaches the verifier, which reads it against the code: a reason, a fix
107
+ // note or neither. All of their replies, so a later "thanks" doesn't hide the reason.
108
+ const all = reply?.replies ?? [];
109
+ const last = all.at(-1);
110
+ // A candidate to keep for later pull requests: written since the latest review (one from before may
111
+ // answer an older round), on code that didn't change since then (the reply may describe the fix),
112
+ // in a thread Mergelight hasn't answered yet (a later reply mustn't overwrite a kept reason, or bring
113
+ // back one forgotten on the dashboard). Whether it is kept is the verifier's call, after the review.
114
+ const fresh = all.filter((r) => latest && Date.parse(r.at) > Date.parse(latest.at));
115
+ // One an earlier review kept, that the server hasn't confirmed: sent again, by at most MAX_TRIES
116
+ // reviews, so one failed report doesn't lose it and a silent server doesn't get it forever.
117
+ const wait = waiting.get(id);
118
+ const open = Boolean(last) && !reply.answered;
119
+ // A later reply, such as a "thanks", doesn't cancel it: the verifier reads all of them again.
120
+ const pending = open && Boolean(wait) && Date.parse(wait.at) <= Date.parse(last.at) && (wait?.tries ?? 1) < MAX_TRIES && (await unchanged(f));
121
+ const remember = pending || (open && fresh.length > 0 && f.status === "open" && (await unchanged(f)));
57
122
  const handled = mark
58
- ? { as: mark.as, note: mark.note, by: mark.by, sha: mark.sha }
59
- : by
60
- ? { as: "wont_fix", note: "Resolved the comment on the pull request.", by, sha: null }
61
- : undefined;
123
+ ? { as: mark.as, note: mark.note, by: mark.by, sha: mark.sha, from: "mark", at: mark.at }
124
+ : by && last
125
+ ? { as: "wont_fix", ...oneLine(all.map((r) => r.text).join("\n\n")), by, sha: null, from: "reply", at: last.at, ...(remember ? { remember: true, ...(pending ? { tries: wait?.tries ?? 1 } : {}) } : {}) }
126
+ : by
127
+ ? { as: "wont_fix", note: RESOLVED_ONLY, by, sha: null, from: "thread" }
128
+ : undefined;
62
129
  return { id, title, file, line, end_line, how, ...(handled ? { handled } : {}) };
130
+ }));
131
+ }
132
+ /** How many reviews send a waiting reason before it is given up on. */
133
+ const MAX_TRIES = 3;
134
+ /**
135
+ * A person's replies as the verifier reads them: one line, nothing hidden, not too long. A long one keeps
136
+ * its end, where the newest reply is: that is the one that counts. cut: it was longer.
137
+ */
138
+ function oneLine(text) {
139
+ const line = withoutHidden(text).replace(/\s+/g, " ").trim();
140
+ return line.length > MAX_NOTE ? { note: `… ${Array.from(line).slice(-(MAX_NOTE - 2)).join("")}`.slice(-MAX_NOTE), cut: true } : { note: line };
141
+ }
142
+ /** The reason the verifier gives when it drops an earlier finding because the team declined it. */
143
+ const TEAM_DECIDED = /\bthe team decided not to fix\b/i;
144
+ /**
145
+ * A reason given in a thread is kept only when the verifier dropped its finding because of it: it read the
146
+ * reply against the code, so a fix note or a plain "ok" isn't kept as a reason not to fix. The others stay
147
+ * what the team said on this pull request, and nothing more.
148
+ */
149
+ export function confirmReasons(previous, rejected) {
150
+ const declined = new Set(rejected.filter((r) => TEAM_DECIDED.test(r.reason)).map((r) => r.candidate));
151
+ return previous?.map((p) => {
152
+ if (p.handled?.from !== "reply" || !p.handled.remember || declined.has(p.id))
153
+ return p;
154
+ const { remember: _remember, tries: _tries, ...handled } = p.handled;
155
+ return { ...p, handled };
63
156
  });
64
157
  }
158
+ /**
159
+ * Answers once in each thread whose reason the server just remembered, so the person sees it was
160
+ * taken. ids: the findings the server stored a decision for.
161
+ */
162
+ export async function answerRemembered(api, number, ids, cut, log = () => { }) {
163
+ if (!ids.length)
164
+ return 0;
165
+ const wanted = new Set(ids);
166
+ let answered = 0;
167
+ // Only in a thread Mergelight started, by the login its summary comment carries, as when it was read.
168
+ const own = (await readPrReviewState(api, number).catch(() => null))?.summary?.user?.login;
169
+ const bare = (login) => login?.replace(/\[bot\]$/, "");
170
+ for (const t of await reviewThreads(api, number).catch(() => [])) {
171
+ const found = threadFinding(t);
172
+ const starter = t.comments.nodes[0]?.author;
173
+ if (!found || starter?.__typename !== "Bot" || (own && bare(starter.login) !== bare(own)) || !wanted.has(found.id) || answeredRemembered(t))
174
+ continue;
175
+ const body = [
176
+ REMEMBERED_MARKER,
177
+ `🧠 **Remembered.** Later reviews of this repository read this reason before they report this problem again.${cut.has(found.id) ? " The reason was long, so only its end, the newest part, is kept." : ""} If it stops being true, forget it on your Mergelight dashboard.`,
178
+ ].join("\n");
179
+ const posted = await api.write("POST", `pulls/${number}/comments/${found.commentId}/replies`, { body }).catch((err) => (log(`Couldn't answer a thread: ${err.message}`), null));
180
+ if (posted !== null)
181
+ answered++;
182
+ }
183
+ return answered;
184
+ }
65
185
  export const CHECK_FAILED_TITLE = "Couldn't review this pull request";
66
186
  export const checkLoginTitle = (plan) => `The ${plan} login didn't work`;
67
187
  export const checkLimitTitle = (plan) => `${CHECK_FAILED_TITLE}: your ${plan} plan hit its limit`;
@@ -190,7 +310,9 @@ export async function publishReview(review, opts = {}) {
190
310
  }
191
311
  }
192
312
  const { handled, resolved } = await settleThreads(api, review, log);
193
- const state = nextState(prev, review.findings, review.pr.head_sha, review.light, urls);
313
+ // A saved review posted later is dated now: replies written since it ran are older than this round.
314
+ const started = opts.startedAt ?? new Date();
315
+ const state = nextState(prev, review.findings, review.pr.head_sha, review.light, urls, Number.isFinite(started.getTime()) ? started : new Date(), opts.remember ?? prev?.remember);
194
316
  const summaryInput = { review, state, urls, marks, handled, update: await newerVersion(api) };
195
317
  const commentBody = summaryBody(summaryInput);
196
318
  let summaryUrl = summary?.html_url ?? null;
@@ -213,9 +335,31 @@ export async function publishReview(review, opts = {}) {
213
335
  },
214
336
  };
215
337
  await writeCheck(api, opts.checkRunId, review.pr.head_sha, check, log);
216
- await syncApproval(api, n, review.light, review.pr.head_sha, log);
338
+ // A review that isn't green takes the approval back for what it found. Only a green one is held by something else.
339
+ const hold = review.light === "green" ? approvalHold(review, opts.teamUnread) : null;
340
+ await syncApproval(api, n, approvalLight(review, opts.teamUnread), review.pr.head_sha, log, hold ? { why: hold } : {});
217
341
  return { summaryUrl, inline: inline.length, outside: outside.length, resolved, light: review.light };
218
342
  }
343
+ /**
344
+ * Why a green review still doesn't approve, in words for the pull request, or null when nothing holds it.
345
+ * One of the team's own checks failed, couldn't tell or couldn't run: Mergelight doesn't approve a
346
+ * pull request that its own check next to it holds back. Or the team's server couldn't be asked: its
347
+ * rules and checks weren't used, so nobody knows what they would have said. A skipped check has nothing to say.
348
+ */
349
+ export function approvalHold(review, teamUnread = false) {
350
+ const held = review.team_checks?.filter((c) => c.outcome !== "pass" && c.outcome !== "skipped") ?? [];
351
+ if (held.length)
352
+ return `Your team's check${held.length === 1 ? "" : "s"} ${held.map((c) => `"${c.name}"`).join(", ")} ${held.length === 1 ? "hasn't" : "haven't"} passed.`;
353
+ if (teamUnread)
354
+ return "Mergelight couldn't reach your team's server, so this review ran without your team's rules and checks.";
355
+ return null;
356
+ }
357
+ /** The light Mergelight's own approval goes by: the review's own, and not green while something holds the approval. */
358
+ export function approvalLight(review, teamUnread = false) {
359
+ return review.light === "green" && approvalHold(review, teamUnread) ? "yellow" : review.light;
360
+ }
361
+ /** What a dismissal says when a review that couldn't run takes Mergelight's earlier approval back. */
362
+ export const UNREVIEWED = "Mergelight couldn't review the newest commit, so its approval of an earlier one no longer stands.";
219
363
  export const APPROVAL_MARKER = "<!-- mergelight:approval -->";
220
364
  /** Only these post Mergelight's reviews, so a person's review that quotes the marker is never touched. */
221
365
  const OWN_REVIEWERS = new Set(["mergelight-ai[bot]", "github-actions[bot]"]);
@@ -224,7 +368,7 @@ const OWN_REVIEWERS = new Set(["mergelight-ai[bot]", "github-actions[bot]"]);
224
368
  * earlier, so an old approval can't stand next to a newer finding. Yellow and red never request changes, so a
225
369
  * review from Mergelight never blocks a merge by itself. Failures only log: the check already carries the result.
226
370
  */
227
- export async function syncApproval(api, number, light, headSha, log = () => { }) {
371
+ export async function syncApproval(api, number, light, headSha, log = () => { }, dismissal = {}) {
228
372
  try {
229
373
  const ours = (await api.list(`pulls/${number}/reviews`)).filter((r) => OWN_REVIEWERS.has(r.user?.login ?? "") && (r.body ?? "").includes(APPROVAL_MARKER));
230
374
  const standing = ours.filter((r) => r.state === "APPROVED");
@@ -238,10 +382,11 @@ export async function syncApproval(api, number, light, headSha, log = () => { })
238
382
  });
239
383
  return "approved";
240
384
  }
241
- for (const r of standing) {
242
- await api.write("PUT", `pulls/${number}/reviews/${r.id}/dismissals`, { message: "A newer Mergelight review found something to look at.", event: "DISMISS" });
385
+ const taken = dismissal.otherCommitsOnly ? standing.filter((r) => r.commit_id !== headSha) : standing;
386
+ for (const r of taken) {
387
+ await api.write("PUT", `pulls/${number}/reviews/${r.id}/dismissals`, { message: dismissal.why ?? "A newer Mergelight review found something to look at.", event: "DISMISS" });
243
388
  }
244
- return standing.length ? "dismissed" : "none";
389
+ return taken.length ? "dismissed" : "none";
245
390
  }
246
391
  catch (err) {
247
392
  log(`Couldn't update Mergelight's approval: ${err instanceof Error ? err.message : String(err)}`);
@@ -253,7 +398,7 @@ export async function reviewThreads(api, number) {
253
398
  repository(owner: $owner, name: $repo) {
254
399
  pullRequest(number: $number) {
255
400
  reviewThreads(first: 100) {
256
- nodes { id isResolved isOutdated resolvedBy { login } comments(first: 50) { nodes { databaseId body authorAssociation author { __typename } } } }
401
+ nodes { id isResolved isOutdated resolvedBy { login } comments(first: 50) { nodes { databaseId body authorAssociation createdAt lastEditedAt author { __typename login } } } }
257
402
  }
258
403
  }
259
404
  }
@@ -336,14 +481,24 @@ export async function latestCheck(api, sha) {
336
481
  const runs = await api.get(`commits/${sha}/check-runs?check_name=${CHECK_NAME}`);
337
482
  return [...runs.check_runs].sort((a, b) => b.id - a.id)[0];
338
483
  }
339
- /** When someone approves a PR with a yellow check, it turns green. A blocked check (a bug to fix) stays red. */
340
- export async function approveCheck(api, number, by) {
484
+ /** When someone approves a PR with a yellow check, it turns green. A blocked check (a bug to fix) stays as it is: only a fix changes it. */
485
+ export async function approveCheck(api, number, by, approvedSha) {
341
486
  const pr = await api.get(`pulls/${number}`);
487
+ // An approval covers the commit the person looked at. Code pushed after it hasn't had its human yet.
488
+ if (approvedSha && approvedSha !== pr.head.sha)
489
+ return `${by} approved an earlier commit, so it doesn't turn the Mergelight check on the newest one green.`;
342
490
  const latest = await latestCheck(api, pr.head.sha);
343
491
  if (!latest)
344
492
  return "No Mergelight check on this commit.";
493
+ // A blocked review ends neutral like a yellow one, so say which it is: an approval doesn't clear a bug.
494
+ if (latest.output.title?.startsWith(LIGHT.red.dot))
495
+ return "The Mergelight check is blocked. An approval doesn't clear it: fix the code and push, and the next review checks it again.";
345
496
  if (!isYellowCheck(latest))
346
497
  return `Mergelight check is ${latest.conclusion ?? "still running"}, nothing to approve.`;
498
+ // GitHub lets anyone who can read a repository leave an approving review. "Needs a human" means a
499
+ // human the team trusts with the code, so only someone who can push turns the check green.
500
+ if (!(await writeAccess(api)(by)))
501
+ return `${by} can't push to this repository, so their approval doesn't turn the Mergelight check green.`;
347
502
  const body = {
348
503
  conclusion: "success",
349
504
  output: {
@@ -38,8 +38,11 @@ export function decodeState(body) {
38
38
  return null;
39
39
  }
40
40
  }
41
- /** Merge this review into the previous state. */
42
- export function nextState(prev, findings, sha, light, urls) {
41
+ /**
42
+ * Merge this review into the previous state. at: when the review started, so whatever people wrote
43
+ * while it ran counts as newer than it.
44
+ */
45
+ export function nextState(prev, findings, sha, light, urls, at = new Date(), remember = []) {
43
46
  const round = (prev?.round ?? 0) + 1;
44
47
  const current = new Set(findings.map((f) => f.id));
45
48
  const before = new Map((prev?.findings ?? []).map((f) => [f.id, f]));
@@ -75,8 +78,9 @@ export function nextState(prev, findings, sha, light, urls) {
75
78
  round,
76
79
  rounds: [
77
80
  ...(prev?.rounds ?? []).slice(-19),
78
- { sha, at: new Date().toISOString(), light, posted: findings.filter((f) => f.tier === "post").length },
81
+ { sha, at: at.toISOString(), light, posted: findings.filter((f) => f.tier === "post").length },
79
82
  ],
80
83
  findings: merged,
84
+ ...(remember.length ? { remember: remember.slice(0, 100) } : {}),
81
85
  };
82
86
  }
@@ -0,0 +1,72 @@
1
+ /** A team's check shows on the pull request under a name of its own, next to the Mergelight check. */
2
+ export const teamCheckName = (name) => `Mergelight: ${name}`;
3
+ /** As code, so nothing in it is read as markup, a link or a mention. */
4
+ const code = (text) => `\`${text.replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, "?")}\``;
5
+ /**
6
+ * Plain text for a check on GitHub. These words come from the AI, which read a pull request someone
7
+ * else wrote, or from the team's server. Neither may post a link, a picture, a mention or markup
8
+ * under Mergelight's name. Short pieces between backticks stay code, which GitHub shows as it is.
9
+ */
10
+ export function plain(text) {
11
+ return text
12
+ .split(/(`[^`\n]+`)/)
13
+ .map((part, i) => i % 2
14
+ ? part
15
+ : part
16
+ .replace(/[\\`*_{}[\]()#+!|<>~&]/g, "\\$&")
17
+ // A zero-width space: the text reads the same, and GitHub no longer sees a mention or a link.
18
+ .replace(/@/g, "@\u200b")
19
+ .replace(/:\/\//g, ":\u200b//")
20
+ .replace(/\bwww\./gi, "www\u200b."))
21
+ .join("")
22
+ .trim();
23
+ }
24
+ /** What GitHub shows for one check: its conclusion, a title, and the reasons. */
25
+ /**
26
+ * A team makes a check stop a merge by requiring it on GitHub, and GitHub lets a neutral check
27
+ * through. So only a real pass is a success: "couldn't tell" and "couldn't run" ask for a person,
28
+ * which a required check doesn't let through. Otherwise the author of a pull request could get past
29
+ * a check by making its run fail.
30
+ */
31
+ export function teamCheckBody(r) {
32
+ const asked = `**The check:** ${code(r.text)}`;
33
+ if (r.outcome === "skipped")
34
+ return { conclusion: "skipped", output: { title: "Not needed: none of its files changed", summary: `${asked}\n\n${r.summary}` } };
35
+ if (r.outcome === "unsure") {
36
+ return { conclusion: "action_required", output: { title: "Couldn't tell: look at this one yourself", summary: `${asked}\n\n${plain(r.summary)}\n\nThis is not a pass. If your team requires this check, it holds the merge until a run can tell.` } };
37
+ }
38
+ if (r.outcome === "error") {
39
+ return { conclusion: "action_required", output: { title: "Couldn't run this check", summary: `${asked}\n\n${plain(r.summary)}\n\nThis is not a pass. If your team requires this check, it holds the merge. Run the review again, or push, to try once more.` } };
40
+ }
41
+ const problems = r.problems.map((p) => `- ${code(p.line ? `${p.file}:${p.line}` : p.file)} ${plain(p.note)}`);
42
+ return {
43
+ conclusion: r.outcome === "pass" ? "success" : "failure",
44
+ output: {
45
+ title: r.outcome === "pass" ? "Passed" : `Failed${r.problems.length ? `: ${r.problems.length} place${r.problems.length === 1 ? "" : "s"} to fix` : ""}`,
46
+ summary: [asked, "", plain(r.summary), ...(problems.length ? ["", ...problems] : [])].join("\n").slice(0, 60_000),
47
+ },
48
+ };
49
+ }
50
+ /**
51
+ * Posts each of the team's checks as a check of its own on the commit. Returns how many were
52
+ * posted. One that can't be posted is logged and doesn't stop the others.
53
+ */
54
+ export async function publishTeamChecks(api, headSha, results, log = () => { }) {
55
+ let posted = 0;
56
+ for (const r of results) {
57
+ try {
58
+ await api.write("POST", "check-runs", { name: teamCheckName(r.name), head_sha: headSha, status: "completed", completed_at: new Date().toISOString(), ...teamCheckBody(r) });
59
+ posted++;
60
+ }
61
+ catch (err) {
62
+ const message = err.message;
63
+ // GitHub only lets Apps write checks, so a personal gh login can't post any of them.
64
+ if (/must authenticate via a GitHub App/i.test(message)) {
65
+ log("Skipped your team's checks: GitHub only lets a GitHub App write checks, not a personal gh login.");
66
+ return posted;
67
+ }
68
+ log(`Couldn't post your team's check "${r.name}": ${message}`);
69
+ }
70
+ }
71
+ return posted;
72
+ }
package/dist/render.js CHANGED
@@ -102,5 +102,28 @@ export function renderTerminal(r) {
102
102
  }
103
103
  if (!r.findings.length)
104
104
  out.push("", green("Nothing worth fixing."));
105
+ if (r.team_checks?.length) {
106
+ out.push("", bold("Your team's checks"));
107
+ for (const c of r.team_checks) {
108
+ const mark = c.outcome === "pass" ? "✅" : c.outcome === "fail" ? "❌" : c.outcome === "skipped" ? "➖" : c.outcome === "unsure" ? "❔" : "⚠️";
109
+ out.push(` ${mark} ${c.name} ${dim(c.summary)}`);
110
+ for (const p of c.problems)
111
+ out.push(dim(` ${p.line ? `${p.file}:${p.line}` : p.file} ${p.note}`));
112
+ }
113
+ }
105
114
  return out.join("\n");
106
115
  }
116
+ /**
117
+ * Each candidate the verifier threw out, with its reason. The review's own comment only keeps what was
118
+ * found, so this is how to answer "why wasn't X reported?". Printed only in debug runs: on a public
119
+ * repository the Action's log is public, and a wrongly rejected candidate can still be a real hole.
120
+ */
121
+ export function renderRejected(r) {
122
+ return r.trace.rejected.map(({ candidate, reason }) => {
123
+ const number = /^C(\d+)$/.exec(candidate)?.[1];
124
+ const c = number ? r.trace.candidates[Number(number) - 1] : undefined;
125
+ // The verifier also rejects earlier rounds' findings, by their own ids.
126
+ const what = c ? `${c.title} (${c.file}:${c.line}, ${c.focus})` : number ? "a candidate the review didn't list" : "an earlier finding";
127
+ return `Rejected ${candidate}: ${what}. Why: ${reason}`;
128
+ });
129
+ }
package/dist/review.js CHANGED
@@ -3,10 +3,12 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { actionsUsedBy, fetchActionSources, notRead } from "./action-source.js";
5
5
  import { fetchPullRequest } from "./github.js";
6
- import { buildHunterPrompt, buildSweepPrompt, buildVerifierPrompt, focusesFor, } from "./prompt.js";
6
+ import { buildCheckPrompt, buildHunterPrompt, buildSweepPrompt, buildVerifierPrompt, focusesFor, ruleApplies, usedMemories, } from "./prompt.js";
7
7
  import { LimitError, LoginError } from "./providers/codex.js";
8
8
  import { claudeAvailable, runModel, TOOLING } from "./providers/index.js";
9
- import { candidateSchema, reviewSchema } from "./schema.js";
9
+ import { candidateSchema, checkSchema, reviewSchema, reviewSchemaWithDecisions } from "./schema.js";
10
+ import { CHECK_TIMEOUT_MS, startTeamChecks } from "./checks.js";
11
+ import { run } from "./run.js";
10
12
  import { cacheDir, prepareWorkspace } from "./workspace.js";
11
13
  /**
12
14
  * Stable id for a finding: the file plus the code it points at, ignoring
@@ -106,6 +108,19 @@ function forProvider(dir, input, provider) {
106
108
  writeFileSync(join(dir, diffFile), input.diff);
107
109
  return { ...input, tooling, diffFile };
108
110
  }
111
+ /** The diff one of the team's checks reads: at most this much of it goes into the question. */
112
+ const MAX_CHECK_DIFF = 150_000;
113
+ /**
114
+ * The whole change to the files a check is about. Unlike the reviewers' diff it leaves nothing out:
115
+ * a check that names a lockfile or a generated file must see what changed in it, removed lines included.
116
+ */
117
+ async function checkDiff(dir, base, head, files) {
118
+ // The names come from git itself and go back to it as they are: never as options, never as patterns.
119
+ const r = await run("git", ["--literal-pathspecs", "-C", dir, "diff", "-U5", "--no-color", "--no-ext-diff", "--no-renames", `${base}...${head}`, "--", ...files.slice(0, 50)], { timeoutMs: 60_000 });
120
+ if (r.code !== 0)
121
+ return { text: "", cut: true, missing: true };
122
+ return r.stdout.length > MAX_CHECK_DIFF ? { text: r.stdout.slice(0, MAX_CHECK_DIFF), cut: true } : { text: r.stdout, cut: files.length > 50 };
123
+ }
109
124
  /**
110
125
  * The verifier: tries to disprove every candidate, merges duplicates, rates the
111
126
  * rest and picks the few that matter most. Exported so the eval can replay the
@@ -115,7 +130,8 @@ export async function verifyCandidates(dir, input, found, opts) {
115
130
  const result = await runModel(opts.provider, {
116
131
  cwd: dir,
117
132
  prompt: buildVerifierPrompt(forProvider(dir, input, opts.provider), found),
118
- schema: reviewSchema,
133
+ // Only a verifier that was given the team's earlier decisions is asked which one it used.
134
+ schema: input.memories?.length ? reviewSchemaWithDecisions : reviewSchema,
119
135
  model: opts.model,
120
136
  effort: opts.effort,
121
137
  logFile: opts.logFile,
@@ -131,6 +147,45 @@ export async function verifyCandidates(dir, input, found, opts) {
131
147
  .sort((a, b) => ORDER[a.class] - ORDER[b.class] || a.file.localeCompare(b.file) || a.line - b.line);
132
148
  return { summary: review.summary, findings, rejected: review.rejected, model: result.model, cost_usd: result.cost_usd ?? null };
133
149
  }
150
+ /** Every rule a team can have for one repository: 50 for the org and 50 of its own. None is dropped. */
151
+ const MAX_RULES = 100;
152
+ /** The summary, with what the reader must know about the team's rules: a guarded file was changed, or the rules couldn't be read. */
153
+ export function summaryWith(summary, needsHuman, rulesUnread) {
154
+ // As code, so a name like __init__.py shows as it is and not as bold text.
155
+ const code = (path) => `\`${path.replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, "?")}\``;
156
+ const guarded = needsHuman.length
157
+ ? ` It changes ${needsHuman.slice(0, 3).map(code).join(", ")}${needsHuman.length > 3 ? ` and ${needsHuman.length - 3} more` : ""}, which your team marked as always needing a human.`
158
+ : "";
159
+ // A team may have rules that would have changed this review. Running without them must never be silent.
160
+ const unread = rulesUnread ? " Mergelight couldn't get your team's rules, skills, checks and earlier decisions from its server, so this review ran without them." : "";
161
+ return `${summary}${guarded}${unread}`;
162
+ }
163
+ /**
164
+ * The light, with the team's "always needs a human" files taken into account. Such a file keeps a
165
+ * pull request from going green by itself. It never makes a light better: red stays red.
166
+ */
167
+ export function lightWith(findings, needsHuman) {
168
+ const light = mergeLight(findings);
169
+ return light === "green" && needsHuman.length ? "yellow" : light;
170
+ }
171
+ /** The changed files that match a "needs a human" rule of the team. */
172
+ export function filesNeedingHuman(rules, changedFiles) {
173
+ const guards = (rules ?? []).filter((r) => r.kind === "needs_human" && r.paths?.length);
174
+ return changedFiles.filter((file) => guards.some((r) => ruleApplies(r, [file])));
175
+ }
176
+ /** Most recent first, as the server sends them. Enough for the files of one pull request, and not a wall of old decisions. */
177
+ const MAX_MEMORIES = 30;
178
+ /**
179
+ * A decision is about one problem in one file, so only those in files this pull request changes are
180
+ * passed on. One made on this very pull request is left out: the verifier already gets it with the
181
+ * earlier rounds, and reviewing its own pull request again must not count as a use that keeps it alive.
182
+ */
183
+ export function memoriesFor(memories, changedFiles, pullRequest) {
184
+ // The same file, however its path was written down: src/a.ts, ./src/a.ts or /src/a.ts.
185
+ const plain = (path) => path.replace(/^(\.\/|\/)+/, "");
186
+ const changed = new Set(changedFiles.map(plain));
187
+ return (memories ?? []).filter((m) => changed.has(plain(m.file)) && m.pr !== pullRequest).slice(0, MAX_MEMORIES);
188
+ }
134
189
  export async function reviewPullRequest(ref, opts = {}) {
135
190
  const started = Date.now();
136
191
  const progress = opts.onProgress ?? (() => { });
@@ -140,9 +195,18 @@ export async function reviewPullRequest(ref, opts = {}) {
140
195
  progress(`Reading ${ref.owner}/${ref.repo}#${ref.number}`);
141
196
  const pr = await fetchPullRequest(ref);
142
197
  progress("Checking out the code");
143
- const ws = await prepareWorkspace(pr, opts.at);
198
+ const ws = await prepareWorkspace(pr, opts.at, opts.skills, opts.writtenSkills);
199
+ const skillsMissing = (opts.skills?.length ?? 0) - ws.skills.length;
200
+ if (skillsMissing > 0)
201
+ progress(`${skillsMissing} of the skill folders your team picked ${skillsMissing === 1 ? "has" : "have"} no SKILL.md on the base branch, or couldn't be read: left out. Name the real folder, not a link to it`);
202
+ const teamSkills = [...ws.skills, ...ws.writtenSkills];
203
+ if (teamSkills.length)
204
+ progress(`Using your team's skill${teamSkills.length === 1 ? "" : "s"}: ${teamSkills.map((s) => s.name).join(", ")}`);
205
+ if (ws.conventions.length)
206
+ progress(`Using ${ws.conventions.map((c) => c.path).join(", ")} from ${pr.baseRef}`);
144
207
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
145
208
  const log = (step) => join(cacheDir(), "logs", `${pr.owner}-${pr.repo}-${pr.number}-${stamp}-${step}.log`);
209
+ let checksRun = null;
146
210
  try {
147
211
  const input = {
148
212
  pr,
@@ -152,6 +216,11 @@ export async function reviewPullRequest(ref, opts = {}) {
152
216
  diff: ws.diff,
153
217
  diffTruncated: ws.diffTruncated,
154
218
  previous: opts.previous,
219
+ memories: memoriesFor(opts.memories, ws.changedFiles.map((f) => f.path), pr.number),
220
+ // Matched against every path the pull request touches, exactly as git has it.
221
+ skills: teamSkills,
222
+ conventions: ws.conventions,
223
+ rules: (opts.rules ?? []).filter((r) => r.kind === "rule" && ruleApplies(r, ws.touchedPaths)).slice(0, MAX_RULES),
155
224
  };
156
225
  // Step 1: hunters, one per area, in parallel. One failing doesn't sink the review.
157
226
  const addedTo = ws.changedFiles.filter((f) => f.added > 0).map((f) => f.path);
@@ -215,6 +284,21 @@ export async function reviewPullRequest(ref, opts = {}) {
215
284
  }
216
285
  });
217
286
  }
287
+ // The team's own checks run next to the verifier. They never fail the review and never hold it up
288
+ // for long: each ends as an answer or as an error of its own.
289
+ const teamChecks = opts.checks?.length
290
+ ? startTeamChecks(opts.checks, ws.touchedPaths, async (check, files) => (await runModel(provider, {
291
+ cwd: ws.dir,
292
+ prompt: buildCheckPrompt({ ...input, tooling: TOOLING[provider] }, check, files, await checkDiff(ws.dir, ws.mergeBase, ws.headSha, files)),
293
+ schema: checkSchema,
294
+ model: hunterModel,
295
+ effort,
296
+ logFile: log(`check-${check.id}`),
297
+ timeoutMs: CHECK_TIMEOUT_MS,
298
+ projectDocs: false,
299
+ })).output, progress)
300
+ : null;
301
+ checksRun = teamChecks;
218
302
  // Step 2: the verifier tries to disprove each candidate and sorts the rest.
219
303
  // Opus checks better than Codex: in the eval it posted a third less and kept the same finds.
220
304
  const verifyWith = opts.verifyWith ?? (provider === "claude" || (await claudeAvailable()) ? "claude" : "codex");
@@ -228,6 +312,9 @@ export async function reviewPullRequest(ref, opts = {}) {
228
312
  logFile: log("verify"),
229
313
  onCommand: (cmd) => progress(`Checking ${found.length} candidates: ${cmd.replace(/\s+/g, " ").slice(0, 80)}`, true),
230
314
  });
315
+ // Every path the pull request touches counts here, the lockfiles and generated files the reviewers skip included.
316
+ const needsHuman = filesNeedingHuman(opts.rules, ws.touchedPaths);
317
+ const team_checks = teamChecks ? await teamChecks.done : null;
231
318
  const firstHunt = hunts.find((h) => h.status === "fulfilled");
232
319
  const servedModel = firstHunt?.status === "fulfilled" ? firstHunt.value.model : null;
233
320
  return {
@@ -243,9 +330,12 @@ export async function reviewPullRequest(ref, opts = {}) {
243
330
  },
244
331
  provider: { name: provider, model: servedModel, effort },
245
332
  verifier: { name: verifyWith, model: verified.model, effort, cost_usd: verified.cost_usd },
246
- light: mergeLight(verified.findings),
247
- summary: verified.summary,
333
+ light: lightWith(verified.findings, needsHuman),
334
+ summary: summaryWith(verified.summary, needsHuman, opts.rulesUnread === true),
335
+ ...(needsHuman.length ? { needs_human: needsHuman } : {}),
248
336
  findings: verified.findings,
337
+ ...(input.memories?.length ? { used_memories: usedMemories(input.memories, verified.rejected, found) } : {}),
338
+ ...(team_checks?.length ? { team_checks } : {}),
249
339
  ...(unread.length ? { not_read: unread } : {}),
250
340
  stats: {
251
341
  duration_ms: Date.now() - started,
@@ -263,6 +353,12 @@ export async function reviewPullRequest(ref, opts = {}) {
263
353
  };
264
354
  }
265
355
  finally {
356
+ // The checkout is about to go. A check that is still waiting for its turn must not start in it.
357
+ // What the checks answered so far goes to the caller, whether the review worked or not.
358
+ if (checksRun) {
359
+ checksRun.stop();
360
+ opts.onTeamChecks?.(await checksRun.done);
361
+ }
266
362
  if (opts.keep)
267
363
  progress(`Kept the checkout at ${ws.dir}`);
268
364
  else