@mergelight/cli 0.1.17 → 0.1.19

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,3 +1,4 @@
1
+ import { LATE_ROUND } from "../types.js";
1
2
  import { encodeState } from "./state.js";
2
3
  export const SUMMARY_MARKER = "<!-- mergelight:summary -->";
3
4
  export const PENDING_MARKER = "<!-- mergelight:pending -->";
@@ -9,6 +10,26 @@ const MAX_BODY = 65_000;
9
10
  * Model text goes into comments, so it must not be able to fake our hidden
10
11
  * markers or ping people.
11
12
  */
13
+ /** Says when the AI the team asked to check had no login yet, so the reviewer's own AI checked instead. */
14
+ export function checkerMissedLine(r) {
15
+ if (!r.checker_missed || r.checker_missed === r.provider.name)
16
+ return null;
17
+ const name = (ai) => (ai === "codex" ? "Codex" : "Claude");
18
+ const login = r.checker_missed === "codex" ? "ChatGPT" : "Claude";
19
+ const why = {
20
+ "no-login": `it has no ${login} login yet`,
21
+ "not-installed": `${name(r.checker_missed)} couldn't be installed on this run`,
22
+ // Codex's could be a ChatGPT login or an OpenAI API key: the run log says which.
23
+ "login-failed": r.checker_missed === "codex" ? "its login didn't work" : `its ${login} login didn't work`,
24
+ // A plan's usage or an API key's credit: it can be either.
25
+ limit: "it hit its usage limit",
26
+ sandbox: `${name(r.checker_missed)}'s sandbox couldn't start on this runner`,
27
+ // Held back on purpose, as one other repositories share: the note says why, and what to do.
28
+ held: "Mergelight held its ChatGPT login back",
29
+ }[r.checker_missed_why ?? "no-login"];
30
+ const then = r.checker_missed_why === "held" && r.checker_missed_note ? ` ${clean(r.checker_missed_note)}` : "";
31
+ return `⚠️ ${name(r.checker_missed)} was set to check this review, but ${why}, so ${name(r.provider.name)} checked it.${then}`;
32
+ }
12
33
  export function clean(text) {
13
34
  return text
14
35
  .replace(/<!--/g, "&lt;!--")
@@ -47,12 +68,57 @@ export function inlineBody(f) {
47
68
  ].join("\n");
48
69
  }
49
70
  /** Posted when a review starts, so the summary is the first thing on the pull request. */
50
- export function pendingSummaryBody() {
51
- return [SUMMARY_MARKER, PENDING_MARKER, "### ⏳ Mergelight: Reviewing", "", "This usually takes 2 to 15 minutes. This comment updates when the review is done."].join("\n");
71
+ /**
72
+ * A model as people read it: "Codex GPT-6.1-Sol", "Claude Opus 5.5". Just the tool's name when the model
73
+ * isn't known, and the model's own name when it isn't one these rules know.
74
+ */
75
+ export function modelLabel(name, model) {
76
+ const brand = name === "codex" ? "Codex" : "Claude";
77
+ // "opus[1m]" asks for the long context, and "claude-opus-5-5@20261101" names a dated build: the
78
+ // model is the part before them.
79
+ const m = model?.trim().replace(/\[[^\]]*\]$/, "").replace(/@[\w.-]*$/, "");
80
+ if (!m || !/^[\w.-]{1,60}$/.test(m))
81
+ return brand;
82
+ const cap = (w) => (/^gpt$/i.test(w) ? "GPT" : w.charAt(0).toUpperCase() + w.slice(1));
83
+ if (name === "codex")
84
+ return `${brand} ${m.split("-").map(cap).join("-")}`;
85
+ // "claude-opus-5-5" and the older "claude-3-7-sonnet" both have a family name and version numbers.
86
+ const parts = m.replace(/^claude-/, "").replace(/-\d{8}$/, "").split("-");
87
+ const family = parts.find((p) => !/^\d+$/.test(p)) ?? "";
88
+ // Claude Code can run another vendor's model: then its own id is the honest name.
89
+ if (family && !/^(?:opus|sonnet|haiku|fable)$/i.test(family))
90
+ return `${brand} (${m})`;
91
+ const version = parts.filter((p) => /^\d+$/.test(p));
92
+ return `${brand}${family ? ` ${cap(family)}` : ""}${version.length ? ` ${version.join(".")}` : ""}`;
93
+ }
94
+ /** A token count as people read it: 812, 45k, 2.9M. */
95
+ export function tokenCount(n) {
96
+ if (n < 1000)
97
+ return String(Math.round(n));
98
+ if (n < 999_500)
99
+ return `${Math.round(n / 1000)}k`;
100
+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
101
+ }
102
+ export function pendingSummaryBody(plan) {
103
+ const reviewer = plan ? modelLabel(plan.reviewer.name, plan.reviewer.model) : null;
104
+ const checker = plan?.checker ? modelLabel(plan.checker.name, plan.checker.model) : null;
105
+ const who = reviewer ? `Reviewing with ${reviewer}${checker && checker !== reviewer ? `, and ${checker} checks the findings` : ""}. ` : "";
106
+ return [SUMMARY_MARKER, PENDING_MARKER, "### ⏳ Mergelight: Reviewing", "", `${who}This usually takes 2 to 15 minutes. This comment updates when the review is done.`].join("\n");
52
107
  }
53
108
  export const isPendingSummary = (body) => Boolean(body?.includes(PENDING_MARKER));
109
+ /** A "Reviewing" comment, not a "Connect your AI" or "install the app" one, which carry the same mark. */
110
+ export const isReviewingSummary = (body) => isPendingSummary(body) && Boolean(body?.includes("### ⏳ Mergelight: Reviewing"));
54
111
  export const loginNotice = (plan, reason) => ({ heading: `⚠️ Mergelight: the ${plan} login didn't work`, body: reason });
112
+ /** For a login held back on purpose: the reason says why and what to do, and nothing is wrong with the login. */
113
+ export const heldLoginNotice = (reason) => ({ heading: "⚠️ Mergelight: the ChatGPT login was held back", body: reason });
55
114
  export function limitNotice(plan, resets) {
115
+ // An API key's credit, not a plan: the fix is adding credit.
116
+ if (plan === "OpenAI") {
117
+ return { heading: "⏳ Mergelight: the OpenAI API key has no usage left", body: "This pull request wasn't reviewed, because the OpenAI API key has no usage left: its credit ran out, or its account reached its spending limit. Check both in the OpenAI account, then push a new commit, and the review runs again." };
118
+ }
119
+ if (plan === "Anthropic") {
120
+ return { heading: "⏳ Mergelight: the Anthropic API key has no credit left", body: "This pull request wasn't reviewed, because the Anthropic API key has no credit left. Add credit to its account, then push a new commit, and the review runs again." };
121
+ }
56
122
  const reason = `This pull request wasn't reviewed, because your ${plan} plan has no usage left.`;
57
123
  return {
58
124
  heading: `⏳ Mergelight: your ${plan} plan hit its limit`,
@@ -62,10 +128,12 @@ export function limitNotice(plan, resets) {
62
128
  /** Marks a summary that only says a run failed, so the next failure can say what's true now. */
63
129
  export const FAILED_MARKER = "<!-- mergelight:failed -->";
64
130
  const GENERAL_FAILURE = ["### ⚠️ Mergelight couldn't review this pull request", "", "The Mergelight check has the reason. The next push tries again."].join("\n");
65
- export function failedSummaryBody(notice) {
131
+ export function failedSummaryBody(notice, jobs) {
132
+ // What the jobs did stays on the pull request when the review fails: the branch changed all the same.
133
+ const after = jobs ? ["", ...jobsLines(jobs)] : [];
66
134
  if (notice)
67
- return [SUMMARY_MARKER, FAILED_MARKER, `### ${notice.heading}`, "", notice.body].join("\n");
68
- return [SUMMARY_MARKER, FAILED_MARKER, GENERAL_FAILURE].join("\n");
135
+ return [SUMMARY_MARKER, FAILED_MARKER, `### ${notice.heading}`, "", notice.body, ...after].join("\n");
136
+ return [SUMMARY_MARKER, FAILED_MARKER, GENERAL_FAILURE, ...after].join("\n");
69
137
  }
70
138
  /** Only at the very start, because a summary with results can quote text from the pull request. Earlier releases wrote no marker. */
71
139
  export const isFailedSummary = (body) => Boolean(body?.startsWith(`${SUMMARY_MARKER}\n${FAILED_MARKER}\n`) || body?.trim() === `${SUMMARY_MARKER}\n${GENERAL_FAILURE}`);
@@ -78,6 +146,26 @@ function duration(ms) {
78
146
  const s = Math.round(ms / 1000);
79
147
  return s >= 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${s}s`;
80
148
  }
149
+ /** Why the loop breaker left a finding alone, in place of the verdict, which may still say to fix it. */
150
+ const LEFT_ALONE_WHY = {
151
+ rare: "Rare, so it doesn't hold the merge.",
152
+ late: `Unlikely, so from round ${LATE_ROUND} on it doesn't hold the merge.`,
153
+ };
154
+ /**
155
+ * From LATE_ROUND on: what the loop breaker left alone, and whether anything still holds the merge. Only
156
+ * likely problems, major bugs and major security problems hold it by then.
157
+ */
158
+ export function loopBreakerLine(r, round) {
159
+ const late = r.findings.filter((f) => f.left_alone === "late").length;
160
+ if (!late)
161
+ return null;
162
+ // A guarded file, or one of the team's own checks that didn't pass, still holds it.
163
+ const teamHolds = r.team_checks?.some((c) => c.outcome !== "pass" && c.outcome !== "skipped");
164
+ if (r.findings.some((f) => f.tier !== "hardening") || r.needs_human?.length || teamHolds) {
165
+ return `Round ${round}: ${late === 1 ? "1 unlikely finding is" : `${late} unlikely findings are`} left alone. From round ${LATE_ROUND} on, only likely problems, major bugs and security problems hold the merge.`;
166
+ }
167
+ return `Round ${round}: only unlikely cases are left, so they don't hold the merge. Merge it.`;
168
+ }
81
169
  function plural(n, word) {
82
170
  return `${n} ${word}${n === 1 ? "" : "s"}`;
83
171
  }
@@ -163,6 +251,44 @@ export function notReadLine(list) {
163
251
  ].filter(Boolean);
164
252
  return `<sub>Not read: ${parts.join(", and ")}.</sub>`;
165
253
  }
254
+ /** What the team's jobs did before this review: each job, and anything that kept their changes off the branch. */
255
+ export function jobsLines(j) {
256
+ const out = ["#### Jobs"];
257
+ const files = (n) => `${n} file${n === 1 ? "" : "s"}`;
258
+ for (const o of j.outcomes) {
259
+ const name = `**${clean(o.name)}**`;
260
+ const said = clean(o.summary);
261
+ // What the job changed while it ran: a later job can undo some of it, so only the pushed commit is the result.
262
+ if (o.status === "changed")
263
+ out.push(`- ✅ ${name}: ${said} (changed ${files(o.files)} while it ran${j.commit ? "" : ", not pushed"})`);
264
+ else if (o.status === "nothing")
265
+ out.push(`- ${name} changed nothing: ${said}`);
266
+ else if (o.status === "refused")
267
+ out.push(`- ⚠️ ${name} was dropped: ${said}`);
268
+ else
269
+ out.push(`- ⚠️ ${name} couldn't finish: ${said}`);
270
+ }
271
+ if (j.skipped)
272
+ out.push(`- ⚠️ No job ran: ${clean(j.skipped)}`);
273
+ if (j.notRun)
274
+ out.push(`- ⚠️ No job ran: ${clean(j.notRun)}`);
275
+ if (j.notPushed)
276
+ out.push(`- ⚠️ Nothing was pushed: ${clean(j.notPushed)}`);
277
+ for (const p of j.problems)
278
+ out.push(`- ⚠️ \`${clean(p.source).replace(/`/g, "")}\` is left out: ${clean(p.problem)}.`);
279
+ if (j.moreProblems)
280
+ out.push(`- ⚠️ ${j.moreProblems} more job file${j.moreProblems === 1 ? " is" : "s are"} left out. The jobs step's log lists ${j.moreProblems === 1 ? "it" : "them"}.`);
281
+ if (j.commit) {
282
+ out.push("",
283
+ // Said to be reviewed only when this review read it; a failed review read nothing.
284
+ j.reviewed === true
285
+ ? `The jobs wrote \`${j.commit.slice(0, 7)}\` with AI, and this review read it like the rest. Pull before you push again.`
286
+ : j.reviewed === false
287
+ ? `The jobs wrote \`${j.commit.slice(0, 7)}\` with AI. This review read another commit, so that one isn't reviewed here. Pull before you push again.`
288
+ : `The jobs wrote \`${j.commit.slice(0, 7)}\` with AI. Pull before you push again.`);
289
+ }
290
+ return out;
291
+ }
166
292
  export function summaryBody({ review: r, state, urls, marks = new Map(), handled = new Map(), update }, withState = true) {
167
293
  const light = LIGHT[r.light];
168
294
  const top = r.findings.filter((f) => f.tier === "post").sort((a, b) => (a.rank ?? 9) - (b.rank ?? 9) || rank(a) - rank(b));
@@ -172,7 +298,10 @@ export function summaryBody({ review: r, state, urls, marks = new Map(), handled
172
298
  const dropped = state.findings.filter((f) => f.status === "gone" && marks.get(f.id)?.as === "wont_fix");
173
299
  const done = state.findings.filter((f) => dropped.includes(f) || (f.status === "gone" && handled.has(f.id)));
174
300
  const gone = state.round > 1 ? state.findings.filter((f) => f.status === "gone" && f.tier !== "hardening" && !done.includes(f)) : [];
175
- const out = [SUMMARY_MARKER, ...(update ? updateBanner(update) : []), `### ${light.dot} Mergelight: ${light.label}`, "", clean(r.summary), "", `**${headline(r, done.length)}**`];
301
+ // The other AI not checking is said first, above the AI's own summary, so a cut never takes it.
302
+ const missed = checkerMissedLine(r);
303
+ const loop = loopBreakerLine(r, state.round);
304
+ const out = [SUMMARY_MARKER, ...(update ? updateBanner(update) : []), `### ${light.dot} Mergelight: ${light.label}`, "", ...(missed ? [missed, ""] : []), clean(r.summary), ...(loop ? ["", loop] : []), "", `**${headline(r, done.length)}**`];
176
305
  if (top.length) {
177
306
  out.push("", "#### To fix");
178
307
  for (const f of top)
@@ -209,7 +338,7 @@ export function summaryBody({ review: r, state, urls, marks = new Map(), handled
209
338
  if (leftAlone.length) {
210
339
  out.push("", `<details><summary>Left alone: ${plural(leftAlone.length, "smaller finding")}</summary>`, "");
211
340
  for (const f of leftAlone)
212
- out.push(`- ${clean(f.title)} ${where(f)}: ${clean(f.verdict)}`);
341
+ out.push(`- ${clean(f.title)} ${where(f)}: ${f.left_alone ? LEFT_ALONE_WHY[f.left_alone] : clean(f.verdict)}`);
213
342
  out.push("", "</details>");
214
343
  }
215
344
  if (gone.length) {
@@ -221,9 +350,14 @@ export function summaryBody({ review: r, state, urls, marks = new Map(), handled
221
350
  const unread = notReadLine(r.not_read);
222
351
  if (unread)
223
352
  out.push("", unread);
224
- const who = (p) => `${p.name === "codex" ? "Codex" : "Claude"}${p.model ? ` ${p.model.replace(/^claude-/, "")}` : ""}`;
225
- const checkedBy = r.verifier && r.verifier.name !== r.provider.name ? `, checked by ${who(r.verifier)},` : "";
226
- out.push("", `<sub>Round ${state.round} · reviewed \`${r.pr.head_sha.slice(0, 7)}\` with ${who(r.provider)}${checkedBy} on your own plan · ${duration(r.stats.duration_ms)}</sub>`);
353
+ if (r.jobs)
354
+ out.push("", ...jobsLines(r.jobs));
355
+ const reviewer = modelLabel(r.provider.name, r.provider.model);
356
+ const checker = r.verifier ? modelLabel(r.verifier.name, r.verifier.model) : reviewer;
357
+ const checkedBy = checker !== reviewer ? `, checked by ${checker},` : "";
358
+ const t = r.stats.tokens;
359
+ const used = t && t.input + t.output > 0 ? ` · ${tokenCount(t.input)} tokens in${t.cached ? ` (${tokenCount(t.cached)} from cache)` : ""}, ${tokenCount(t.output)} out` : "";
360
+ out.push("", `<sub>Round ${state.round} · reviewed \`${r.pr.head_sha.slice(0, 7)}\` with ${reviewer}${checkedBy} on your own plan · ${duration(r.stats.duration_ms)}${used}</sub>`);
227
361
  const tail = withState ? `\n${encodeState(state)}` : "";
228
362
  const room = MAX_BODY - tail.length;
229
363
  let body = out.join("\n");
@@ -1,11 +1,11 @@
1
1
  import { RESOLVED_ONLY } from "../prompt.js";
2
- import { GitHub } from "./api.js";
2
+ import { GitHub, TRANSIENT } from "./api.js";
3
3
  import { commentableLines, place } from "./diff-lines.js";
4
4
  import { answeredRemembered, closedBody, patchTouches, readClosed, REMEMBERED_MARKER, reopenedBody, resolvedByPeople, resolverReplies, threadAction, threadFinding } from "./closed.js";
5
- import { failedSummaryBody, FINDING_MARKER_RE, headline, inlineBody, isFailedSummary, isPendingSummary, LIGHT, pendingSummaryBody, SUMMARY_MARKER, summaryBody } from "./markdown.js";
5
+ import { jobsLines, failedSummaryBody, FINDING_MARKER_RE, headline, inlineBody, isFailedSummary, isPendingSummary, isReviewingSummary, LIGHT, pendingSummaryBody, SUMMARY_MARKER, summaryBody } from "./markdown.js";
6
6
  import { askWriteAccess, MAX_NOTE, readMarks, trustedComment, writeAccess } from "./handled.js";
7
7
  import { withoutHidden } from "../skills.js";
8
- import { decodeState, nextState } from "./state.js";
8
+ import { decodeState, nextState, stateBlock } from "./state.js";
9
9
  import { newerVersion } from "../update.js";
10
10
  export { trustedComment } from "./handled.js";
11
11
  export const CHECK_NAME = "Mergelight";
@@ -87,6 +87,10 @@ function unchangedSince(api, since, headSha) {
87
87
  * headSha: the commit this review is about, to tell a reason from a fix.
88
88
  */
89
89
  export async function previousFindings(api, number, headSha) {
90
+ return (await previousReview(api, number, headSha)).findings;
91
+ }
92
+ /** What earlier rounds found, and how many rounds there were: the next review is round + 1. */
93
+ export async function previousReview(api, number, headSha) {
90
94
  const { summary, state, marks } = await readPrReviewState(api, number);
91
95
  const threads = await reviewThreads(api, number).catch(() => []);
92
96
  const resolved = await resolvedByPeople(threads, writeAccess(api));
@@ -98,7 +102,7 @@ export async function previousFindings(api, number, headSha) {
98
102
  // A decision not to fix must reach the verifier however long the list gets, or the problem comes back as new.
99
103
  const order = (f) => (marks.get(f.id)?.as === "wont_fix" || resolved.has(f.id) ? 0 : f.status === "gone" ? 2 : 1);
100
104
  const kept = (state?.findings ?? []).sort((a, b) => order(a) - order(b)).slice(0, MAX_PREVIOUS);
101
- return Promise.all(kept.map(async (f) => {
105
+ const findings = await Promise.all(kept.map(async (f) => {
102
106
  const { id, title, file, line, end_line, how } = f;
103
107
  const mark = marks.get(id);
104
108
  const by = resolved.get(id);
@@ -128,6 +132,7 @@ export async function previousFindings(api, number, headSha) {
128
132
  : undefined;
129
133
  return { id, title, file, line, end_line, how, ...(handled ? { handled } : {}) };
130
134
  }));
135
+ return { findings, round: state?.round ?? 0 };
131
136
  }
132
137
  /** How many reviews send a waiting reason before it is given up on. */
133
138
  const MAX_TRIES = 3;
@@ -184,7 +189,8 @@ export async function answerRemembered(api, number, ids, cut, log = () => { }) {
184
189
  }
185
190
  export const CHECK_FAILED_TITLE = "Couldn't review this pull request";
186
191
  export const checkLoginTitle = (plan) => `The ${plan} login didn't work`;
187
- export const checkLimitTitle = (plan) => `${CHECK_FAILED_TITLE}: your ${plan} plan hit its limit`;
192
+ export const checkHeldTitle = `${CHECK_FAILED_TITLE}: the ChatGPT login was held back`;
193
+ export const checkLimitTitle = (plan) => (plan === "OpenAI" || plan === "Anthropic" ? `${CHECK_FAILED_TITLE}: the ${plan} API key has no usage left` : `${CHECK_FAILED_TITLE}: your ${plan} plan hit its limit`);
188
194
  export const isFailedCheckTitle = (title) => Boolean(title && (title.startsWith(CHECK_FAILED_TITLE) || /^The \w+ login didn't work$/.test(title)));
189
195
  /**
190
196
  * Creates the check, or updates it if it has an id. GitHub only lets Apps write
@@ -208,40 +214,92 @@ export async function writeCheck(api, id, headSha, body, log) {
208
214
  * Shows a live "Reviewing" check right away, so people and agents can see work is
209
215
  * happening. A login that can't write checks hears about it once, from the last write.
210
216
  */
211
- export async function startCheck(api, headSha) {
217
+ export async function startCheck(api, headSha, provider, handedOver, started) {
218
+ const tool = provider === "claude" ? "Claude" : provider === "codex" ? "Codex" : null;
219
+ // Always a check of the review's own, for the commit it reads: approvals and verdicts then go to the
220
+ // check this review made, never to an older one.
212
221
  const run = await writeCheck(api, null, headSha, {
213
222
  status: "in_progress",
214
223
  started_at: new Date().toISOString(),
215
224
  output: {
216
225
  title: "Reviewing",
217
- summary: "Mergelight is reviewing this pull request with Codex on your own plan. This usually takes 2 to 15 minutes.",
226
+ summary: `Mergelight is reviewing this pull request${tool ? ` with ${tool}` : ""} on your own plan. This usually takes 2 to 15 minutes.`,
218
227
  },
219
228
  });
229
+ // Known before anything else is asked, so a run cancelled from here on still finishes it.
230
+ if (run?.id)
231
+ started?.(run.id);
232
+ // A connect's check left going for this review is closed only now, with this one already going, so
233
+ // there is no moment without a running check, and none with both. Only a check still running: a
234
+ // finished one's verdict stands. It is this run's own, made for this pull request, so also when a push
235
+ // during the sign-in moved the review to a newer commit. One that can't be read or closed here is
236
+ // finished by the Action's last step.
237
+ const old = handedOver ? await api.get(`check-runs/${handedOver}`).catch(() => null) : null;
238
+ if (handedOver && old && old.status !== "completed") {
239
+ const moved = old.head_sha !== headSha;
240
+ await writeCheck(api, handedOver, old.head_sha, {
241
+ status: "completed",
242
+ conclusion: "neutral",
243
+ completed_at: new Date().toISOString(),
244
+ output: { title: "Superseded", summary: moved ? `A newer commit was pushed while Mergelight waited, so it reviews ${headSha.slice(0, 7)} instead.` : "The review goes on in a new check." },
245
+ }).catch(() => null);
246
+ }
220
247
  return run?.id ?? null;
221
248
  }
222
249
  /** Puts the summary comment on the PR before anything else, so it comes first. Later rounds edit it in place. */
223
- export async function startSummary(api, number) {
250
+ export async function startSummary(api, number, plan, ownPrompt) {
224
251
  const { summary } = await readPrReviewState(api, number);
225
- return summary ?? (await api.write("POST", `issues/${number}/comments`, { body: pendingSummaryBody() }));
252
+ // A "Reviewing" comment left by an earlier run, or by a reconnect, says this run's plan now, keeping its
253
+ // state. So does this run's own prompt to connect the AI that checks: the review starts without it, and
254
+ // its code or link is dead by now. Another run's prompt may still be waiting, so it stays.
255
+ const checkerPrompt = Boolean(ownPrompt) && isPendingSummary(summary?.body) && Boolean(summary?.body?.includes('"for":"check"')) && Boolean(summary?.body?.includes(ownPrompt));
256
+ if (summary && plan && (isReviewingSummary(summary.body) || checkerPrompt)) {
257
+ const state = stateBlock(summary.body);
258
+ const body = state ? `${pendingSummaryBody(plan)}\n${state}` : pendingSummaryBody(plan);
259
+ if (body !== summary.body)
260
+ await api.write("PATCH", `issues/comments/${summary.id}`, { body }).catch(() => null);
261
+ return { ...summary, body };
262
+ }
263
+ return summary ?? (await api.write("POST", `issues/${number}/comments`, { body: pendingSummaryBody(plan) }));
264
+ }
265
+ /** Names the models in a "Reviewing" comment once they are known. A comment with a result is left alone. */
266
+ export async function updatePendingSummary(api, summary, plan) {
267
+ if (!summary || !isReviewingSummary(summary.body))
268
+ return;
269
+ // Read it again: another run may have finished and written its result since this one began.
270
+ const now = await api.get(`issues/comments/${summary.id}`).catch(() => null);
271
+ if (!now || !isReviewingSummary(now.body))
272
+ return;
273
+ // A "Reviewing" comment can carry earlier rounds' state, after a reconnect: it must stay, or the next
274
+ // result starts again from round 1.
275
+ const state = stateBlock(now.body);
276
+ await api.write("PATCH", `issues/comments/${summary.id}`, { body: state ? `${pendingSummaryBody(plan)}\n${state}` : pendingSummaryBody(plan) });
226
277
  }
227
278
  /** A first review that couldn't run shouldn't say "Reviewing" forever, and an older failure shouldn't outlive a newer reason. Real results stay. */
228
- export async function failSummary(api, number, notice) {
279
+ export async function failSummary(api, number, notice, jobs) {
229
280
  const { summary } = await readPrReviewState(api, number);
230
- if (summary && (isPendingSummary(summary.body) || isFailedSummary(summary.body)))
231
- await api.write("PATCH", `issues/comments/${summary.id}`, { body: failedSummaryBody(notice) });
281
+ // An earlier review's finished summary is left alone: writing over it could undo a newer run's result.
282
+ // The check for this commit says what the jobs did instead (failCheck).
283
+ if (!summary || !(isPendingSummary(summary.body) || isFailedSummary(summary.body)))
284
+ return;
285
+ // A pending summary can carry what earlier rounds found, such as one a login prompt replaced: it stays.
286
+ const state = stateBlock(summary.body);
287
+ await api.write("PATCH", `issues/comments/${summary.id}`, { body: state ? `${failedSummaryBody(notice, jobs)}\n${state}` : failedSummaryBody(notice, jobs) });
232
288
  }
233
289
  /**
234
290
  * A review that couldn't run ends neutral, so a broken login doesn't block
235
291
  * merging. The workflow job itself still fails, so it's visible.
236
292
  */
237
- export async function failCheck(api, checkRunId, headSha, reason, log, title = CHECK_FAILED_TITLE) {
293
+ export async function failCheck(api, checkRunId, headSha, reason, log, title = CHECK_FAILED_TITLE, jobs) {
294
+ // What the jobs did, when they ran: the branch changed all the same, and the check is this commit's own.
295
+ const jobsPart = jobs ? `\n\n${jobsLines(jobs).join("\n").slice(0, 20_000)}` : "";
238
296
  await writeCheck(api, checkRunId, headSha, {
239
297
  status: "completed",
240
298
  conclusion: "neutral",
241
299
  completed_at: new Date().toISOString(),
242
300
  output: {
243
301
  title,
244
- summary: `${reason.slice(0, 2000)}\n\nThis check is neutral so a broken review doesn't block merging. The workflow log has the details.`,
302
+ summary: `${reason.slice(0, 2000)}\n\nThis check is neutral so a broken review doesn't block merging. The workflow log has the details.${jobsPart}`,
245
303
  },
246
304
  }, log);
247
305
  }
@@ -406,13 +464,17 @@ export async function reviewThreads(api, number) {
406
464
  repository(owner: $owner, name: $repo) {
407
465
  pullRequest(number: $number) {
408
466
  reviewThreads(first: 100) {
409
- nodes { id isResolved isOutdated resolvedBy { login } comments(first: 50) { nodes { databaseId body authorAssociation createdAt lastEditedAt author { __typename login } } } }
467
+ nodes { id isResolved isOutdated resolvedBy { login } comments(first: 50) { nodes { id isMinimized minimizedReason databaseId body authorAssociation createdAt lastEditedAt author { __typename login } } } }
410
468
  }
411
469
  }
412
470
  }
413
471
  }`, { owner: api.owner, repo: api.repo, number });
414
472
  return data?.repository.pullRequest.reviewThreads.nodes ?? [];
415
473
  }
474
+ /** Folds a comment away as resolved. Needs only the right to write pull request comments. */
475
+ const minimizeComment = (api, id) => api.graphql(`mutation($id: ID!) { minimizeComment(input: { subjectId: $id, classifier: RESOLVED }) { minimizedComment { isMinimized } } }`, { id }, true);
476
+ /** Shows a folded comment again. */
477
+ const unminimizeComment = (api, id) => api.graphql(`mutation($id: ID!) { unminimizeComment(input: { subjectId: $id }) { unminimizedComment { isMinimized } } }`, { id }, true);
416
478
  export const resolveThread = (api, id) => api.graphql(`mutation($id: ID!) { resolveReviewThread(input: { threadId: $id }) { thread { id } } }`, { id }, true);
417
479
  const unresolveThread = (api, id) => api.graphql(`mutation($id: ID!) { unresolveReviewThread(input: { threadId: $id }) { thread { id } } }`, { id }, true);
418
480
  /**
@@ -434,7 +496,13 @@ async function settleThreads(api, review, log) {
434
496
  const open = new Set(review.findings.map((f) => f.id));
435
497
  const sha = review.pr.head_sha.slice(0, 7);
436
498
  const canWrite = writeAccess(api);
437
- const edit = (commentId, body) => api.write("PATCH", `pulls/comments/${commentId}`, { body }).catch((err) => log(`Couldn't update a comment: ${err.message}`));
499
+ /** Who this token belongs to, asked once if needed. Null for an app or a workflow token. */
500
+ let viewer;
501
+ /** True when the comment was changed. */
502
+ const edit = (commentId, body) => api.write("PATCH", `pulls/comments/${commentId}`, { body }).then(() => true, (err) => {
503
+ log(`Couldn't update a comment: ${err.message}`);
504
+ return false;
505
+ });
438
506
  for (const t of threads) {
439
507
  const found = threadFinding(t);
440
508
  if (!found)
@@ -449,6 +517,7 @@ async function settleThreads(api, review, log) {
449
517
  }
450
518
  if (action.kind === "fixed") {
451
519
  let isResolved = !action.resolve;
520
+ let fold = false;
452
521
  if (action.resolve) {
453
522
  try {
454
523
  await resolveThread(api, t.id);
@@ -456,13 +525,39 @@ async function settleThreads(api, review, log) {
456
525
  resolved++;
457
526
  }
458
527
  catch (err) {
459
- // GitHub only lets a workflow token resolve threads with contents: write. The comment still says it's handled.
460
- const hint = /not accessible by integration/i.test(err.message) ? "the workflow needs contents: write for that" : err.message;
461
- log(`Couldn't mark a fixed thread resolved: ${hint}`);
528
+ const message = err.message;
529
+ // GitHub only lets a token resolve a thread when it may also write code, which Mergelight's may
530
+ // not, and says so in different words for an app and for a personal token. Then the fixed comment
531
+ // is folded away as resolved instead, if Mergelight wrote it. Only a passing error (GitHub down, a
532
+ // timeout, a rate limit) leaves the thread for the next review to try again.
533
+ const passing = TRANSIENT.test(message);
534
+ if (!passing) {
535
+ log(`Couldn't mark a fixed thread resolved: ${message}`);
536
+ // Mergelight's own comment: the app's bot, or the login of a personal token.
537
+ const author = t.comments.nodes[0]?.author;
538
+ let own = author?.__typename === "Bot";
539
+ if (!own && author?.login) {
540
+ if (viewer === undefined)
541
+ viewer = await api.viewer();
542
+ own = author.login === viewer;
543
+ }
544
+ // A comment someone already hid keeps their reason.
545
+ fold = Boolean(found.nodeId) && own && !t.comments.nodes[0]?.isMinimized;
546
+ }
547
+ else {
548
+ // Left as it was, not marked Handled: a marked thread isn't tried again, and this one should be.
549
+ log(`Couldn't mark a fixed thread resolved: ${message}. The next review tries again.`);
550
+ continue;
551
+ }
462
552
  }
463
553
  }
464
554
  handled.set(found.id, { how: "fixed", sha });
465
- await edit(found.commentId, closedBody(found.body, { how: "fixed", resolved: isResolved, sha }));
555
+ const edited = await edit(found.commentId, closedBody(found.body, { how: "fixed", resolved: isResolved, sha }));
556
+ // Only once it says Handled: a finding that comes back unfolds by that mark, so without it the
557
+ // comment would stay hidden.
558
+ if (fold && edited) {
559
+ await minimizeComment(api, found.nodeId).then(() => log("Folded a fixed finding's comment away as resolved."), (e) => log(`Couldn't fold a fixed finding's comment away: ${e.message}`));
560
+ }
466
561
  }
467
562
  else if (action.kind === "resolved") {
468
563
  // A workflow token sees a private org member as CONTRIBUTOR, so ask who can write instead of trusting the association.
@@ -475,6 +570,20 @@ async function settleThreads(api, review, log) {
475
570
  if (action.kind === "regressed" && action.unresolve) {
476
571
  await unresolveThread(api, t.id).catch((err) => log(`Couldn't reopen a thread: ${err.message}`));
477
572
  }
573
+ // A finding that came back shows its comment again if Mergelight folded it: Mergelight only folds a
574
+ // comment marked fixed and not resolved, so one a person hid, or folded on a thread they resolved,
575
+ // stays hidden. If unfolding fails, the marker stays, so the next review tries again.
576
+ const first = t.comments.nodes[0];
577
+ const closed = readClosed(found.body);
578
+ const folded = closed?.how === "fixed" && !closed.resolved && first?.isMinimized && /^resolved$/i.test(first.minimizedReason ?? "");
579
+ if (folded && found.nodeId) {
580
+ const shown = await unminimizeComment(api, found.nodeId).then(() => true, (err) => {
581
+ log(`Couldn't unfold a comment: ${err.message}`);
582
+ return false;
583
+ });
584
+ if (!shown)
585
+ continue;
586
+ }
478
587
  await edit(found.commentId, reopenedBody(found.body, action.kind === "reopened"));
479
588
  }
480
589
  }
@@ -4,7 +4,7 @@ const MARKER = "mergelight:state:v1";
4
4
  const MAX_STATE = 40_000;
5
5
  const pack = (state) => `<!-- ${MARKER} ${gzipSync(JSON.stringify(state)).toString("base64")} -->`;
6
6
  function withoutDetails(f) {
7
- const { likelihood: _l, what_breaks: _w, fix: _f, fix_cost: _c, verdict: _v, rank: _r, ...rest } = f;
7
+ const { likelihood: _l, what_breaks: _w, fix: _f, fix_cost: _c, verdict: _v, rank: _r, security: _s, ...rest } = f;
8
8
  return rest;
9
9
  }
10
10
  function withoutHow(f) {
@@ -59,6 +59,7 @@ export function nextState(prev, findings, sha, light, urls, at = new Date(), rem
59
59
  end_line: f.end_line,
60
60
  how: f.how_it_happens,
61
61
  likelihood: f.likelihood,
62
+ ...(f.security !== undefined ? { security: f.security } : {}),
62
63
  what_breaks: f.what_breaks,
63
64
  fix: f.fix,
64
65
  fix_cost: f.fix_cost,