@mergelight/cli 0.1.18 → 0.1.20

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;!--")
@@ -88,7 +109,16 @@ export const isPendingSummary = (body) => Boolean(body?.includes(PENDING_MARKER)
88
109
  /** A "Reviewing" comment, not a "Connect your AI" or "install the app" one, which carry the same mark. */
89
110
  export const isReviewingSummary = (body) => isPendingSummary(body) && Boolean(body?.includes("### ⏳ Mergelight: Reviewing"));
90
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 });
91
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
+ }
92
122
  const reason = `This pull request wasn't reviewed, because your ${plan} plan has no usage left.`;
93
123
  return {
94
124
  heading: `⏳ Mergelight: your ${plan} plan hit its limit`,
@@ -98,10 +128,12 @@ export function limitNotice(plan, resets) {
98
128
  /** Marks a summary that only says a run failed, so the next failure can say what's true now. */
99
129
  export const FAILED_MARKER = "<!-- mergelight:failed -->";
100
130
  const GENERAL_FAILURE = ["### ⚠️ Mergelight couldn't review this pull request", "", "The Mergelight check has the reason. The next push tries again."].join("\n");
101
- 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)] : [];
102
134
  if (notice)
103
- return [SUMMARY_MARKER, FAILED_MARKER, `### ${notice.heading}`, "", notice.body].join("\n");
104
- 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");
105
137
  }
106
138
  /** Only at the very start, because a summary with results can quote text from the pull request. Earlier releases wrote no marker. */
107
139
  export const isFailedSummary = (body) => Boolean(body?.startsWith(`${SUMMARY_MARKER}\n${FAILED_MARKER}\n`) || body?.trim() === `${SUMMARY_MARKER}\n${GENERAL_FAILURE}`);
@@ -114,6 +146,26 @@ function duration(ms) {
114
146
  const s = Math.round(ms / 1000);
115
147
  return s >= 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${s}s`;
116
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
+ }
117
169
  function plural(n, word) {
118
170
  return `${n} ${word}${n === 1 ? "" : "s"}`;
119
171
  }
@@ -199,6 +251,44 @@ export function notReadLine(list) {
199
251
  ].filter(Boolean);
200
252
  return `<sub>Not read: ${parts.join(", and ")}.</sub>`;
201
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
+ }
202
292
  export function summaryBody({ review: r, state, urls, marks = new Map(), handled = new Map(), update }, withState = true) {
203
293
  const light = LIGHT[r.light];
204
294
  const top = r.findings.filter((f) => f.tier === "post").sort((a, b) => (a.rank ?? 9) - (b.rank ?? 9) || rank(a) - rank(b));
@@ -208,7 +298,10 @@ export function summaryBody({ review: r, state, urls, marks = new Map(), handled
208
298
  const dropped = state.findings.filter((f) => f.status === "gone" && marks.get(f.id)?.as === "wont_fix");
209
299
  const done = state.findings.filter((f) => dropped.includes(f) || (f.status === "gone" && handled.has(f.id)));
210
300
  const gone = state.round > 1 ? state.findings.filter((f) => f.status === "gone" && f.tier !== "hardening" && !done.includes(f)) : [];
211
- 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)}**`];
212
305
  if (top.length) {
213
306
  out.push("", "#### To fix");
214
307
  for (const f of top)
@@ -245,7 +338,7 @@ export function summaryBody({ review: r, state, urls, marks = new Map(), handled
245
338
  if (leftAlone.length) {
246
339
  out.push("", `<details><summary>Left alone: ${plural(leftAlone.length, "smaller finding")}</summary>`, "");
247
340
  for (const f of leftAlone)
248
- 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)}`);
249
342
  out.push("", "</details>");
250
343
  }
251
344
  if (gone.length) {
@@ -257,6 +350,8 @@ export function summaryBody({ review: r, state, urls, marks = new Map(), handled
257
350
  const unread = notReadLine(r.not_read);
258
351
  if (unread)
259
352
  out.push("", unread);
353
+ if (r.jobs)
354
+ out.push("", ...jobsLines(r.jobs));
260
355
  const reviewer = modelLabel(r.provider.name, r.provider.model);
261
356
  const checker = r.verifier ? modelLabel(r.verifier.name, r.verifier.model) : reviewer;
262
357
  const checkedBy = checker !== reviewer ? `, checked by ${checker},` : "";
@@ -1,8 +1,8 @@
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, isReviewingSummary, 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
8
  import { decodeState, nextState, stateBlock } from "./state.js";
@@ -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,8 +214,10 @@ 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, provider) {
217
+ export async function startCheck(api, headSha, provider, handedOver, started) {
212
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.
213
221
  const run = await writeCheck(api, null, headSha, {
214
222
  status: "in_progress",
215
223
  started_at: new Date().toISOString(),
@@ -218,13 +226,34 @@ export async function startCheck(api, headSha, provider) {
218
226
  summary: `Mergelight is reviewing this pull request${tool ? ` with ${tool}` : ""} on your own plan. This usually takes 2 to 15 minutes.`,
219
227
  },
220
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
+ }
221
247
  return run?.id ?? null;
222
248
  }
223
249
  /** Puts the summary comment on the PR before anything else, so it comes first. Later rounds edit it in place. */
224
- export async function startSummary(api, number, plan) {
250
+ export async function startSummary(api, number, plan, ownPrompt) {
225
251
  const { summary } = await readPrReviewState(api, number);
226
- // A "Reviewing" comment left by an earlier run, or by a reconnect, says this run's plan now, keeping its state.
227
- if (summary && plan && isReviewingSummary(summary.body)) {
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)) {
228
257
  const state = stateBlock(summary.body);
229
258
  const body = state ? `${pendingSummaryBody(plan)}\n${state}` : pendingSummaryBody(plan);
230
259
  if (body !== summary.body)
@@ -247,23 +276,30 @@ export async function updatePendingSummary(api, summary, plan) {
247
276
  await api.write("PATCH", `issues/comments/${summary.id}`, { body: state ? `${pendingSummaryBody(plan)}\n${state}` : pendingSummaryBody(plan) });
248
277
  }
249
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. */
250
- export async function failSummary(api, number, notice) {
279
+ export async function failSummary(api, number, notice, jobs) {
251
280
  const { summary } = await readPrReviewState(api, number);
252
- if (summary && (isPendingSummary(summary.body) || isFailedSummary(summary.body)))
253
- 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) });
254
288
  }
255
289
  /**
256
290
  * A review that couldn't run ends neutral, so a broken login doesn't block
257
291
  * merging. The workflow job itself still fails, so it's visible.
258
292
  */
259
- 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)}` : "";
260
296
  await writeCheck(api, checkRunId, headSha, {
261
297
  status: "completed",
262
298
  conclusion: "neutral",
263
299
  completed_at: new Date().toISOString(),
264
300
  output: {
265
301
  title,
266
- 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}`,
267
303
  },
268
304
  }, log);
269
305
  }
@@ -428,13 +464,17 @@ export async function reviewThreads(api, number) {
428
464
  repository(owner: $owner, name: $repo) {
429
465
  pullRequest(number: $number) {
430
466
  reviewThreads(first: 100) {
431
- 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 } } } }
432
468
  }
433
469
  }
434
470
  }
435
471
  }`, { owner: api.owner, repo: api.repo, number });
436
472
  return data?.repository.pullRequest.reviewThreads.nodes ?? [];
437
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);
438
478
  export const resolveThread = (api, id) => api.graphql(`mutation($id: ID!) { resolveReviewThread(input: { threadId: $id }) { thread { id } } }`, { id }, true);
439
479
  const unresolveThread = (api, id) => api.graphql(`mutation($id: ID!) { unresolveReviewThread(input: { threadId: $id }) { thread { id } } }`, { id }, true);
440
480
  /**
@@ -456,7 +496,13 @@ async function settleThreads(api, review, log) {
456
496
  const open = new Set(review.findings.map((f) => f.id));
457
497
  const sha = review.pr.head_sha.slice(0, 7);
458
498
  const canWrite = writeAccess(api);
459
- 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
+ });
460
506
  for (const t of threads) {
461
507
  const found = threadFinding(t);
462
508
  if (!found)
@@ -471,6 +517,7 @@ async function settleThreads(api, review, log) {
471
517
  }
472
518
  if (action.kind === "fixed") {
473
519
  let isResolved = !action.resolve;
520
+ let fold = false;
474
521
  if (action.resolve) {
475
522
  try {
476
523
  await resolveThread(api, t.id);
@@ -478,13 +525,39 @@ async function settleThreads(api, review, log) {
478
525
  resolved++;
479
526
  }
480
527
  catch (err) {
481
- // GitHub only lets a workflow token resolve threads with contents: write. The comment still says it's handled.
482
- const hint = /not accessible by integration/i.test(err.message) ? "the workflow needs contents: write for that" : err.message;
483
- 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
+ }
484
552
  }
485
553
  }
486
554
  handled.set(found.id, { how: "fixed", sha });
487
- 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
+ }
488
561
  }
489
562
  else if (action.kind === "resolved") {
490
563
  // A workflow token sees a private org member as CONTRIBUTOR, so ask who can write instead of trusting the association.
@@ -497,6 +570,20 @@ async function settleThreads(api, review, log) {
497
570
  if (action.kind === "regressed" && action.unresolve) {
498
571
  await unresolveThread(api, t.id).catch((err) => log(`Couldn't reopen a thread: ${err.message}`));
499
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
+ }
500
587
  await edit(found.commentId, reopenedBody(found.body, action.kind === "reopened"));
501
588
  }
502
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,