@mergelight/cli 0.0.0-stage ā 0.1.15
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.
- package/LICENSE.md +110 -0
- package/README.md +113 -2
- package/dist/action-source.js +107 -0
- package/dist/checks.js +108 -0
- package/dist/cli.js +296 -0
- package/dist/cloud.js +330 -0
- package/dist/connect-claude.js +157 -0
- package/dist/connect.js +319 -0
- package/dist/github.js +65 -0
- package/dist/init.js +92 -0
- package/dist/mcp/findings.js +252 -0
- package/dist/mcp/server.js +168 -0
- package/dist/prompt.js +503 -0
- package/dist/providers/claude.js +102 -0
- package/dist/providers/codex.js +251 -0
- package/dist/providers/index.js +8 -0
- package/dist/publish/api.js +63 -0
- package/dist/publish/closed.js +88 -0
- package/dist/publish/diff-lines.js +50 -0
- package/dist/publish/handled.js +98 -0
- package/dist/publish/markdown.js +233 -0
- package/dist/publish/publish.js +397 -0
- package/dist/publish/state.js +82 -0
- package/dist/publish/team-checks.js +72 -0
- package/dist/render.js +129 -0
- package/dist/review.js +366 -0
- package/dist/run.js +57 -0
- package/dist/schema.js +155 -0
- package/dist/setup.js +180 -0
- package/dist/skills.js +127 -0
- package/dist/types.js +1 -0
- package/dist/update.js +36 -0
- package/dist/workspace.js +318 -0
- package/package.json +36 -4
- package/scripts/app-token.mjs +69 -0
- package/scripts/mask-login.mjs +26 -0
- package/scripts/refresh-login.mjs +171 -0
- package/scripts/save-claude-login.sh +22 -0
- package/scripts/save-login.sh +30 -0
- package/skills/mergelight/SKILL.md +66 -0
- package/templates/mergelight-approve.yml +21 -0
- package/templates/mergelight-refresh.yml +23 -0
- package/templates/mergelight.yml +42 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { encodeState } from "./state.js";
|
|
2
|
+
export const SUMMARY_MARKER = "<!-- mergelight:summary -->";
|
|
3
|
+
export const PENDING_MARKER = "<!-- mergelight:pending -->";
|
|
4
|
+
export const findingMarker = (id) => `<!-- mergelight:finding id=${id} -->`;
|
|
5
|
+
export const FINDING_MARKER_RE = /<!-- mergelight:finding id=([a-f0-9]+) -->/;
|
|
6
|
+
/** GitHub's limit for a comment body and a check run summary. */
|
|
7
|
+
const MAX_BODY = 65_000;
|
|
8
|
+
/**
|
|
9
|
+
* Model text goes into comments, so it must not be able to fake our hidden
|
|
10
|
+
* markers or ping people.
|
|
11
|
+
*/
|
|
12
|
+
export function clean(text) {
|
|
13
|
+
return text
|
|
14
|
+
.replace(/<!--/g, "<!--")
|
|
15
|
+
.replace(/(^|[^\w`])@(?=[A-Za-z0-9-])/g, "$1@ā")
|
|
16
|
+
.trim();
|
|
17
|
+
}
|
|
18
|
+
export function label(f) {
|
|
19
|
+
if (f.class === "bug")
|
|
20
|
+
return f.severity === "minor" ? { dot: "š ", name: "Minor bug" } : { dot: "š“", name: "Bug" };
|
|
21
|
+
if (f.class === "risk")
|
|
22
|
+
return { dot: "š”", name: "Risk" };
|
|
23
|
+
return { dot: "āŖ", name: "Small fix" };
|
|
24
|
+
}
|
|
25
|
+
/** Display order: bugs, then risks, then minor bugs, then small fixes. */
|
|
26
|
+
export function rank(f) {
|
|
27
|
+
if (f.class === "bug")
|
|
28
|
+
return f.severity === "minor" ? 2 : 0;
|
|
29
|
+
return f.class === "risk" ? 1 : 3;
|
|
30
|
+
}
|
|
31
|
+
const where = (f) => `\`${f.file}:${f.end_line > f.line ? `${f.line}-${f.end_line}` : f.line}\``;
|
|
32
|
+
export function inlineBody(f) {
|
|
33
|
+
const { dot, name } = label(f);
|
|
34
|
+
return [
|
|
35
|
+
findingMarker(f.id),
|
|
36
|
+
`${dot} **${name}** Ā· **${clean(f.title)}**`,
|
|
37
|
+
"",
|
|
38
|
+
clean(f.how_it_happens),
|
|
39
|
+
"",
|
|
40
|
+
`**What breaks:** ${clean(f.what_breaks)}`,
|
|
41
|
+
"",
|
|
42
|
+
`**Smallest fix** (${f.fix_cost}): ${clean(f.fix)}`,
|
|
43
|
+
"",
|
|
44
|
+
`**ā ${clean(f.verdict)}**`,
|
|
45
|
+
"",
|
|
46
|
+
`<sub>${f.likelihood} Ā· ${f.severity} Ā· fix ${f.fix_cost}</sub>`,
|
|
47
|
+
].join("\n");
|
|
48
|
+
}
|
|
49
|
+
/** 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");
|
|
52
|
+
}
|
|
53
|
+
export const isPendingSummary = (body) => Boolean(body?.includes(PENDING_MARKER));
|
|
54
|
+
export const loginNotice = (plan, reason) => ({ heading: `ā ļø Mergelight: the ${plan} login didn't work`, body: reason });
|
|
55
|
+
export function limitNotice(plan, resets) {
|
|
56
|
+
const reason = `This pull request wasn't reviewed, because your ${plan} plan has no usage left.`;
|
|
57
|
+
return {
|
|
58
|
+
heading: `ā³ Mergelight: your ${plan} plan hit its limit`,
|
|
59
|
+
body: resets ? `${reason}\n\n**Resets:** ${resets}\n\nPush a new commit after that, and the review runs again.` : `${reason}\n\nPush a new commit once your plan has usage again, and the review runs again.`,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Marks a summary that only says a run failed, so the next failure can say what's true now. */
|
|
63
|
+
export const FAILED_MARKER = "<!-- mergelight:failed -->";
|
|
64
|
+
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) {
|
|
66
|
+
if (notice)
|
|
67
|
+
return [SUMMARY_MARKER, FAILED_MARKER, `### ${notice.heading}`, "", notice.body].join("\n");
|
|
68
|
+
return [SUMMARY_MARKER, FAILED_MARKER, GENERAL_FAILURE].join("\n");
|
|
69
|
+
}
|
|
70
|
+
/** Only at the very start, because a summary with results can quote text from the pull request. Earlier releases wrote no marker. */
|
|
71
|
+
export const isFailedSummary = (body) => Boolean(body?.startsWith(`${SUMMARY_MARKER}\n${FAILED_MARKER}\n`) || body?.trim() === `${SUMMARY_MARKER}\n${GENERAL_FAILURE}`);
|
|
72
|
+
export const LIGHT = {
|
|
73
|
+
red: { dot: "š“", label: "Blocked" },
|
|
74
|
+
yellow: { dot: "š”", label: "Needs a human" },
|
|
75
|
+
green: { dot: "š¢", label: "Safe to merge" },
|
|
76
|
+
};
|
|
77
|
+
function duration(ms) {
|
|
78
|
+
const s = Math.round(ms / 1000);
|
|
79
|
+
return s >= 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${s}s`;
|
|
80
|
+
}
|
|
81
|
+
function plural(n, word) {
|
|
82
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
83
|
+
}
|
|
84
|
+
/** One line on what the review found, for the summary and the check title. */
|
|
85
|
+
export function headline(r, handled = 0) {
|
|
86
|
+
const toFix = r.findings.filter((f) => f.tier === "post" || f.tier === "list");
|
|
87
|
+
const bugs = toFix.filter((f) => f.class === "bug" && f.severity !== "minor").length;
|
|
88
|
+
const minor = toFix.filter((f) => f.class === "bug" && f.severity === "minor").length;
|
|
89
|
+
const risks = toFix.filter((f) => f.class !== "bug").length;
|
|
90
|
+
const decisions = r.findings.filter((f) => f.tier === "decision").length;
|
|
91
|
+
const parts = [];
|
|
92
|
+
if (bugs)
|
|
93
|
+
parts.push(plural(bugs, "bug"));
|
|
94
|
+
if (risks)
|
|
95
|
+
parts.push(plural(risks, "risk"));
|
|
96
|
+
if (minor)
|
|
97
|
+
parts.push(plural(minor, "minor bug"));
|
|
98
|
+
const fix = parts.length ? `${parts.join(", ")} to fix` : "";
|
|
99
|
+
const call = decisions ? `${decisions} for you to decide` : "";
|
|
100
|
+
// A guarded file is why this one needs a human, when nothing else is: "Nothing worth fixing" would contradict the light.
|
|
101
|
+
const guarded = r.needs_human?.length ? "Changes a file that always needs a human" : "";
|
|
102
|
+
return [fix, call].filter(Boolean).join(", ") || guarded || (handled ? "Nothing left to fix" : "Nothing worth fixing");
|
|
103
|
+
}
|
|
104
|
+
/** A finding this review still reports, though someone marked it handled before the review finished. */
|
|
105
|
+
function markTag(mark) {
|
|
106
|
+
if (!mark)
|
|
107
|
+
return "";
|
|
108
|
+
return mark.as === "fixed" ? " _(marked fixed, still found)_" : " _(marked won't fix, still reported)_";
|
|
109
|
+
}
|
|
110
|
+
const escapeHtml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
111
|
+
/** A title as HTML: escaped, with its `code` kept, and no one mentioned by accident. */
|
|
112
|
+
const inlineHtml = (text) => clean(escapeHtml(text)).replace(/`([^`]+)`/g, "<code>$1</code>");
|
|
113
|
+
/** A line for a finding worth fixing. Without an inline comment to link to, the details go here. */
|
|
114
|
+
function fixLine(f, urls, mark) {
|
|
115
|
+
const { dot, name } = label(f);
|
|
116
|
+
const url = urls.get(f.id);
|
|
117
|
+
const tag = markTag(mark);
|
|
118
|
+
if (url)
|
|
119
|
+
return [`- ${dot} ${name}: [${clean(f.title)}](${url}) ${where(f)}${tag}`];
|
|
120
|
+
// Markdown doesn't work inside <summary>, so this line is HTML.
|
|
121
|
+
const markNote = mark ? ` <i>(${mark.as === "fixed" ? "marked fixed, still found" : "marked won't fix, still reported"})</i>` : "";
|
|
122
|
+
return [
|
|
123
|
+
"",
|
|
124
|
+
`<details><summary>${dot} ${name}: <b>${inlineHtml(f.title)}</b> <code>${escapeHtml(where(f).replaceAll("`", ""))}</code>${markNote}</summary>`,
|
|
125
|
+
"",
|
|
126
|
+
clean(f.how_it_happens),
|
|
127
|
+
"",
|
|
128
|
+
`**What breaks:** ${clean(f.what_breaks)}`,
|
|
129
|
+
"",
|
|
130
|
+
`**Smallest fix** (${f.fix_cost}): ${clean(f.fix)}`,
|
|
131
|
+
"",
|
|
132
|
+
`**ā ${clean(f.verdict)}**`,
|
|
133
|
+
"",
|
|
134
|
+
"</details>",
|
|
135
|
+
];
|
|
136
|
+
}
|
|
137
|
+
const NEWS_SHOWN = 4;
|
|
138
|
+
/** At the top of the comment, because a pinned repo only gets new versions if someone notices and acts. */
|
|
139
|
+
function updateBanner({ tag, current, news }) {
|
|
140
|
+
const more = news.length - NEWS_SHOWN;
|
|
141
|
+
return [
|
|
142
|
+
"> [!IMPORTANT]",
|
|
143
|
+
`> **You're missing out: Mergelight ${tag} is out, and this repo is on ${current}.**`,
|
|
144
|
+
...(news.length ? [">", ...news.slice(0, NEWS_SHOWN).map((n) => `> - ${clean(n)}`), ...(more > 0 ? [`> - and ${more} more`] : [])] : []),
|
|
145
|
+
">",
|
|
146
|
+
"> **[Update now](https://mergelight.dev/setup/)**. It's one click, and only the version lines change.",
|
|
147
|
+
"",
|
|
148
|
+
];
|
|
149
|
+
}
|
|
150
|
+
/** Says what the review couldn't see, so a quiet result isn't taken to cover it. The names are checked against a strict pattern before they get here. */
|
|
151
|
+
export function notReadLine(list) {
|
|
152
|
+
if (!list?.length)
|
|
153
|
+
return null;
|
|
154
|
+
const names = (items) => {
|
|
155
|
+
const shown = items.slice(0, 4).map((i) => `\`${i.uses.replace(/[^\w./@-]/g, "")}\``);
|
|
156
|
+
return items.length > 4 ? `${shown.join(", ")} and ${items.length - 4} more` : shown.join(", ");
|
|
157
|
+
};
|
|
158
|
+
const programs = list.filter((i) => i.why === "program");
|
|
159
|
+
const missing = list.filter((i) => i.why === "unreadable");
|
|
160
|
+
const parts = [
|
|
161
|
+
programs.length ? `the code that ${names(programs)} ${programs.length === 1 ? "runs" : "run"} (a Node or Docker action, so only ${programs.length === 1 ? "its definition was" : "their definitions were"} read)` : "",
|
|
162
|
+
missing.length ? `${names(missing)} (couldn't be read)` : "",
|
|
163
|
+
].filter(Boolean);
|
|
164
|
+
return `<sub>Not read: ${parts.join(", and ")}.</sub>`;
|
|
165
|
+
}
|
|
166
|
+
export function summaryBody({ review: r, state, urls, marks = new Map(), handled = new Map(), update }, withState = true) {
|
|
167
|
+
const light = LIGHT[r.light];
|
|
168
|
+
const top = r.findings.filter((f) => f.tier === "post").sort((a, b) => (a.rank ?? 9) - (b.rank ?? 9) || rank(a) - rank(b));
|
|
169
|
+
const listed = r.findings.filter((f) => f.tier === "list").sort((a, b) => rank(a) - rank(b));
|
|
170
|
+
const decisions = r.findings.filter((f) => f.tier === "decision");
|
|
171
|
+
const leftAlone = r.findings.filter((f) => f.tier === "hardening");
|
|
172
|
+
const dropped = state.findings.filter((f) => f.status === "gone" && marks.get(f.id)?.as === "wont_fix");
|
|
173
|
+
const done = state.findings.filter((f) => dropped.includes(f) || (f.status === "gone" && handled.has(f.id)));
|
|
174
|
+
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)}**`];
|
|
176
|
+
if (top.length) {
|
|
177
|
+
out.push("", "#### To fix");
|
|
178
|
+
for (const f of top)
|
|
179
|
+
out.push(...fixLine(f, urls, marks.get(f.id)));
|
|
180
|
+
}
|
|
181
|
+
if (listed.length) {
|
|
182
|
+
// With nothing above it, the count is the heading already, and "also" would point at an empty section.
|
|
183
|
+
out.push("", ...(top.length ? ["#### Also worth fixing"] : []));
|
|
184
|
+
for (const f of listed)
|
|
185
|
+
out.push(...fixLine(f, urls, marks.get(f.id)));
|
|
186
|
+
}
|
|
187
|
+
if (decisions.length) {
|
|
188
|
+
out.push("", "#### Your call", "Real, but whether to fix it is a trade-off for you to make.", "");
|
|
189
|
+
for (const f of decisions) {
|
|
190
|
+
out.push(`- **${clean(f.title)}** ${where(f)}: ${clean(f.verdict)}${markTag(marks.get(f.id))}`);
|
|
191
|
+
out.push(` <details><summary>How it happens</summary>`, "", ` ${clean(f.how_it_happens)} ${clean(f.what_breaks)}`, "", ` Fix (${f.fix_cost}): ${clean(f.fix)}`, " </details>");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (done.length) {
|
|
195
|
+
out.push("", `<details><summary>ā
Handled: ${done.length}</summary>`, "");
|
|
196
|
+
for (const f of done) {
|
|
197
|
+
const mark = marks.get(f.id);
|
|
198
|
+
const h = handled.get(f.id);
|
|
199
|
+
const how = mark?.as === "wont_fix"
|
|
200
|
+
? `not fixing. ${clean(mark.note ?? "No reason given.")} (${mark.by})`
|
|
201
|
+
: h?.how === "fixed"
|
|
202
|
+
? `fixed${h.sha ? ` in \`${h.sha}\`` : ""}`
|
|
203
|
+
: `resolved${h?.by ? ` by ${h.by}` : ""}`;
|
|
204
|
+
const url = urls.get(f.id) ?? f.url;
|
|
205
|
+
out.push(`- ā
${url ? `[${clean(f.title)}](${url})` : clean(f.title)} \`${f.file}:${f.line}\`: ${how}`);
|
|
206
|
+
}
|
|
207
|
+
out.push("", "</details>");
|
|
208
|
+
}
|
|
209
|
+
if (leftAlone.length) {
|
|
210
|
+
out.push("", `<details><summary>Left alone: ${plural(leftAlone.length, "smaller finding")}</summary>`, "");
|
|
211
|
+
for (const f of leftAlone)
|
|
212
|
+
out.push(`- ${clean(f.title)} ${where(f)}: ${clean(f.verdict)}`);
|
|
213
|
+
out.push("", "</details>");
|
|
214
|
+
}
|
|
215
|
+
if (gone.length) {
|
|
216
|
+
out.push("", `<details><summary>No longer found since the last review: ${gone.length}</summary>`, "");
|
|
217
|
+
for (const f of gone)
|
|
218
|
+
out.push(`- ${clean(f.title)} \`${f.file}:${f.line}\``);
|
|
219
|
+
out.push("", "</details>");
|
|
220
|
+
}
|
|
221
|
+
const unread = notReadLine(r.not_read);
|
|
222
|
+
if (unread)
|
|
223
|
+
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>`);
|
|
227
|
+
const tail = withState ? `\n${encodeState(state)}` : "";
|
|
228
|
+
const room = MAX_BODY - tail.length;
|
|
229
|
+
let body = out.join("\n");
|
|
230
|
+
if (body.length > room)
|
|
231
|
+
body = `${body.slice(0, room - 200)}\n\n_Summary cut short: too many findings to list._`;
|
|
232
|
+
return `${body}${tail}`;
|
|
233
|
+
}
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { GitHub } from "./api.js";
|
|
2
|
+
import { commentableLines, place } from "./diff-lines.js";
|
|
3
|
+
import { closedBody, readClosed, reopenedBody, resolvedByPeople, threadAction, threadFinding } from "./closed.js";
|
|
4
|
+
import { failedSummaryBody, FINDING_MARKER_RE, headline, inlineBody, isFailedSummary, isPendingSummary, LIGHT, pendingSummaryBody, SUMMARY_MARKER, summaryBody } from "./markdown.js";
|
|
5
|
+
import { askWriteAccess, readMarks, trustedComment, writeAccess } from "./handled.js";
|
|
6
|
+
import { decodeState, nextState } from "./state.js";
|
|
7
|
+
import { newerVersion } from "../update.js";
|
|
8
|
+
export { trustedComment } from "./handled.js";
|
|
9
|
+
export const CHECK_NAME = "Mergelight";
|
|
10
|
+
/**
|
|
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).
|
|
15
|
+
*/
|
|
16
|
+
export function checkConclusion(light, yellowBlocks = false) {
|
|
17
|
+
if (light === "green")
|
|
18
|
+
return "success";
|
|
19
|
+
if (light === "red")
|
|
20
|
+
return "failure";
|
|
21
|
+
return yellowBlocks ? "action_required" : "neutral";
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The summary comment, which Mergelight edits and reads its state from. Only a bot's comment or the
|
|
25
|
+
* current login's own counts. A person's association isn't enough: a teammate who wrote the marker
|
|
26
|
+
* could edit the comment later, and change a login code people are told to enter.
|
|
27
|
+
*/
|
|
28
|
+
export async function ownSummary(comments, viewer) {
|
|
29
|
+
const marked = comments.filter((c) => c.body?.includes(SUMMARY_MARKER));
|
|
30
|
+
const bots = marked.find((c) => c.user?.type === "Bot");
|
|
31
|
+
if (bots || !marked.length)
|
|
32
|
+
return bots;
|
|
33
|
+
const me = await viewer();
|
|
34
|
+
return me ? marked.find((c) => c.user?.login === me) : undefined;
|
|
35
|
+
}
|
|
36
|
+
/** What Mergelight has on this PR so far. Reviews read it before they publish, and the MCP server hands it to agents. */
|
|
37
|
+
export async function readPrReviewState(api, number) {
|
|
38
|
+
const issueComments = await api.list(`issues/${number}/comments`);
|
|
39
|
+
const reviewComments = await api.list(`pulls/${number}/comments`);
|
|
40
|
+
const summary = await ownSummary(issueComments, () => api.viewer());
|
|
41
|
+
const marks = await readMarks([...issueComments, ...reviewComments], askWriteAccess(api));
|
|
42
|
+
return { summary, state: decodeState(summary?.body), marks, reviewComments };
|
|
43
|
+
}
|
|
44
|
+
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));
|
|
49
|
+
// A decision not to fix must reach the verifier however long the list gets, or the problem comes back as new.
|
|
50
|
+
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 }) => {
|
|
55
|
+
const mark = marks.get(id);
|
|
56
|
+
const by = resolved.get(id);
|
|
57
|
+
const handled = mark
|
|
58
|
+
? { as: mark.as, note: mark.note, by: mark.by, sha: mark.sha, from: "mark", at: mark.at }
|
|
59
|
+
: by
|
|
60
|
+
? { as: "wont_fix", note: "Resolved the comment on the pull request.", by, sha: null, from: "thread" }
|
|
61
|
+
: undefined;
|
|
62
|
+
return { id, title, file, line, end_line, how, ...(handled ? { handled } : {}) };
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export const CHECK_FAILED_TITLE = "Couldn't review this pull request";
|
|
66
|
+
export const checkLoginTitle = (plan) => `The ${plan} login didn't work`;
|
|
67
|
+
export const checkLimitTitle = (plan) => `${CHECK_FAILED_TITLE}: your ${plan} plan hit its limit`;
|
|
68
|
+
export const isFailedCheckTitle = (title) => Boolean(title && (title.startsWith(CHECK_FAILED_TITLE) || /^The \w+ login didn't work$/.test(title)));
|
|
69
|
+
/**
|
|
70
|
+
* Creates the check, or updates it if it has an id. GitHub only lets Apps write
|
|
71
|
+
* checks, so a personal `gh` login gets a 403 on any repository. That doesn't sink
|
|
72
|
+
* a review, since the comments carry it. Every other error still throws.
|
|
73
|
+
*/
|
|
74
|
+
export async function writeCheck(api, id, headSha, body, log) {
|
|
75
|
+
try {
|
|
76
|
+
if (id)
|
|
77
|
+
return await api.write("PATCH", `check-runs/${id}`, body);
|
|
78
|
+
return await api.write("POST", "check-runs", { name: CHECK_NAME, head_sha: headSha, ...body });
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (!/must authenticate via a GitHub App/i.test(err.message))
|
|
82
|
+
throw err;
|
|
83
|
+
log?.("Skipped the Mergelight check: GitHub only lets a GitHub App write checks, not a personal gh login.");
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Shows a live "Reviewing" check right away, so people and agents can see work is
|
|
89
|
+
* happening. A login that can't write checks hears about it once, from the last write.
|
|
90
|
+
*/
|
|
91
|
+
export async function startCheck(api, headSha) {
|
|
92
|
+
const run = await writeCheck(api, null, headSha, {
|
|
93
|
+
status: "in_progress",
|
|
94
|
+
started_at: new Date().toISOString(),
|
|
95
|
+
output: {
|
|
96
|
+
title: "Reviewing",
|
|
97
|
+
summary: "Mergelight is reviewing this pull request with Codex on your own plan. This usually takes 2 to 15 minutes.",
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
return run?.id ?? null;
|
|
101
|
+
}
|
|
102
|
+
/** Puts the summary comment on the PR before anything else, so it comes first. Later rounds edit it in place. */
|
|
103
|
+
export async function startSummary(api, number) {
|
|
104
|
+
const { summary } = await readPrReviewState(api, number);
|
|
105
|
+
return summary ?? (await api.write("POST", `issues/${number}/comments`, { body: pendingSummaryBody() }));
|
|
106
|
+
}
|
|
107
|
+
/** 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. */
|
|
108
|
+
export async function failSummary(api, number, notice) {
|
|
109
|
+
const { summary } = await readPrReviewState(api, number);
|
|
110
|
+
if (summary && (isPendingSummary(summary.body) || isFailedSummary(summary.body)))
|
|
111
|
+
await api.write("PATCH", `issues/comments/${summary.id}`, { body: failedSummaryBody(notice) });
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* A review that couldn't run ends neutral, so a broken login doesn't block
|
|
115
|
+
* merging. The workflow job itself still fails, so it's visible.
|
|
116
|
+
*/
|
|
117
|
+
export async function failCheck(api, checkRunId, headSha, reason, log, title = CHECK_FAILED_TITLE) {
|
|
118
|
+
await writeCheck(api, checkRunId, headSha, {
|
|
119
|
+
status: "completed",
|
|
120
|
+
conclusion: "neutral",
|
|
121
|
+
completed_at: new Date().toISOString(),
|
|
122
|
+
output: {
|
|
123
|
+
title,
|
|
124
|
+
summary: `${reason.slice(0, 2000)}\n\nThis check is neutral so a broken review doesn't block merging. The workflow log has the details.`,
|
|
125
|
+
},
|
|
126
|
+
}, log);
|
|
127
|
+
}
|
|
128
|
+
export async function publishReview(review, opts = {}) {
|
|
129
|
+
const log = opts.log ?? (() => { });
|
|
130
|
+
const api = new GitHub(review.pr.owner, review.pr.repo, opts);
|
|
131
|
+
const n = review.pr.number;
|
|
132
|
+
// What's already on the PR: the summary comment with last round's state, and inline findings.
|
|
133
|
+
const { summary: existing, state: prev, marks, reviewComments } = await readPrReviewState(api, n);
|
|
134
|
+
// The summary goes up before the inline comments, so it stays on top of them.
|
|
135
|
+
const summary = existing ?? (await api.write("POST", `issues/${n}/comments`, { body: pendingSummaryBody() }));
|
|
136
|
+
const urls = new Map();
|
|
137
|
+
for (const c of reviewComments) {
|
|
138
|
+
if (!trustedComment(c))
|
|
139
|
+
continue;
|
|
140
|
+
const id = c.body.match(FINDING_MARKER_RE)?.[1];
|
|
141
|
+
if (id && !urls.has(id))
|
|
142
|
+
urls.set(id, c.html_url);
|
|
143
|
+
}
|
|
144
|
+
// New top picks go inline, if their lines are in the diff. A finding from an earlier
|
|
145
|
+
// round stays where it is, even if the verifier ranks it higher now: the reader has
|
|
146
|
+
// seen it, and a new comment on old code is just more noise.
|
|
147
|
+
const lines = await commentableLines(api, n);
|
|
148
|
+
const seen = new Set(prev?.findings.map((f) => f.id));
|
|
149
|
+
const fresh = review.findings.filter((f) => f.tier === "post" && !urls.has(f.id) && !seen.has(f.id));
|
|
150
|
+
const inline = [];
|
|
151
|
+
const outside = [];
|
|
152
|
+
for (const f of fresh) {
|
|
153
|
+
const at = place(lines, f.file, f.line, f.end_line);
|
|
154
|
+
if (!at) {
|
|
155
|
+
outside.push(f);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
inline.push({
|
|
159
|
+
f,
|
|
160
|
+
comment: {
|
|
161
|
+
path: f.file,
|
|
162
|
+
side: "RIGHT",
|
|
163
|
+
line: at.line,
|
|
164
|
+
...(at.start_line ? { start_line: at.start_line, start_side: "RIGHT" } : {}),
|
|
165
|
+
body: inlineBody(f),
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
if (inline.length) {
|
|
170
|
+
const body = {
|
|
171
|
+
commit_id: review.pr.head_sha,
|
|
172
|
+
event: "COMMENT",
|
|
173
|
+
comments: inline.map((i) => i.comment),
|
|
174
|
+
};
|
|
175
|
+
try {
|
|
176
|
+
const posted = await api.write("POST", `pulls/${n}/reviews`, body);
|
|
177
|
+
if (posted) {
|
|
178
|
+
for (const c of await api.list(`pulls/${n}/reviews/${posted.id}/comments`)) {
|
|
179
|
+
const id = c.body.match(FINDING_MARKER_RE)?.[1];
|
|
180
|
+
if (id)
|
|
181
|
+
urls.set(id, c.html_url);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch (err) {
|
|
186
|
+
// One line GitHub won't take rejects the whole review. List them in the summary instead.
|
|
187
|
+
log(`Inline review rejected, listing findings in the summary instead: ${err.message}`);
|
|
188
|
+
outside.push(...inline.map((i) => i.f));
|
|
189
|
+
inline.length = 0;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const { handled, resolved } = await settleThreads(api, review, log);
|
|
193
|
+
const state = nextState(prev, review.findings, review.pr.head_sha, review.light, urls);
|
|
194
|
+
const summaryInput = { review, state, urls, marks, handled, update: await newerVersion(api) };
|
|
195
|
+
const commentBody = summaryBody(summaryInput);
|
|
196
|
+
let summaryUrl = summary?.html_url ?? null;
|
|
197
|
+
if (summary) {
|
|
198
|
+
await api.write("PATCH", `issues/comments/${summary.id}`, { body: commentBody });
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
const created = await api.write("POST", `issues/${n}/comments`, { body: commentBody });
|
|
202
|
+
summaryUrl = created?.html_url ?? null;
|
|
203
|
+
}
|
|
204
|
+
const light = LIGHT[review.light];
|
|
205
|
+
const check = {
|
|
206
|
+
status: "completed",
|
|
207
|
+
conclusion: checkConclusion(review.light, opts.yellowBlocks),
|
|
208
|
+
completed_at: new Date().toISOString(),
|
|
209
|
+
...(summaryUrl ? { details_url: summaryUrl } : {}),
|
|
210
|
+
output: {
|
|
211
|
+
title: `${light.dot} ${light.label}: ${headline(review, handled.size)}`,
|
|
212
|
+
summary: summaryBody(summaryInput, false).replace(SUMMARY_MARKER, "").slice(0, 65_000),
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
await writeCheck(api, opts.checkRunId, review.pr.head_sha, check, log);
|
|
216
|
+
// A review that isn't green takes the approval back for what it found. Only a green one is held by something else.
|
|
217
|
+
const hold = review.light === "green" ? approvalHold(review, opts.teamUnread) : null;
|
|
218
|
+
await syncApproval(api, n, approvalLight(review, opts.teamUnread), review.pr.head_sha, log, hold ? { why: hold } : {});
|
|
219
|
+
return { summaryUrl, inline: inline.length, outside: outside.length, resolved, light: review.light };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Why a green review still doesn't approve, in words for the pull request, or null when nothing holds it.
|
|
223
|
+
* One of the team's own checks failed, couldn't tell or couldn't run: Mergelight doesn't approve a
|
|
224
|
+
* pull request that its own check next to it holds back. Or the team's server couldn't be asked: its
|
|
225
|
+
* rules and checks weren't used, so nobody knows what they would have said. A skipped check has nothing to say.
|
|
226
|
+
*/
|
|
227
|
+
export function approvalHold(review, teamUnread = false) {
|
|
228
|
+
const held = review.team_checks?.filter((c) => c.outcome !== "pass" && c.outcome !== "skipped") ?? [];
|
|
229
|
+
if (held.length)
|
|
230
|
+
return `Your team's check${held.length === 1 ? "" : "s"} ${held.map((c) => `"${c.name}"`).join(", ")} ${held.length === 1 ? "hasn't" : "haven't"} passed.`;
|
|
231
|
+
if (teamUnread)
|
|
232
|
+
return "Mergelight couldn't reach your team's server, so this review ran without your team's rules and checks.";
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
/** The light Mergelight's own approval goes by: the review's own, and not green while something holds the approval. */
|
|
236
|
+
export function approvalLight(review, teamUnread = false) {
|
|
237
|
+
return review.light === "green" && approvalHold(review, teamUnread) ? "yellow" : review.light;
|
|
238
|
+
}
|
|
239
|
+
/** What a dismissal says when a review that couldn't run takes Mergelight's earlier approval back. */
|
|
240
|
+
export const UNREVIEWED = "Mergelight couldn't review the newest commit, so its approval of an earlier one no longer stands.";
|
|
241
|
+
export const APPROVAL_MARKER = "<!-- mergelight:approval -->";
|
|
242
|
+
/** Only these post Mergelight's reviews, so a person's review that quotes the marker is never touched. */
|
|
243
|
+
const OWN_REVIEWERS = new Set(["mergelight-ai[bot]", "github-actions[bot]"]);
|
|
244
|
+
/**
|
|
245
|
+
* Green approves the pull request, like a reviewer would. Anything else takes back an approval Mergelight gave
|
|
246
|
+
* earlier, so an old approval can't stand next to a newer finding. Yellow and red never request changes, so a
|
|
247
|
+
* review from Mergelight never blocks a merge by itself. Failures only log: the check already carries the result.
|
|
248
|
+
*/
|
|
249
|
+
export async function syncApproval(api, number, light, headSha, log = () => { }, dismissal = {}) {
|
|
250
|
+
try {
|
|
251
|
+
const ours = (await api.list(`pulls/${number}/reviews`)).filter((r) => OWN_REVIEWERS.has(r.user?.login ?? "") && (r.body ?? "").includes(APPROVAL_MARKER));
|
|
252
|
+
const standing = ours.filter((r) => r.state === "APPROVED");
|
|
253
|
+
if (light === "green") {
|
|
254
|
+
if (standing.some((r) => r.commit_id === headSha))
|
|
255
|
+
return "already";
|
|
256
|
+
await api.write("POST", `pulls/${number}/reviews`, {
|
|
257
|
+
commit_id: headSha,
|
|
258
|
+
event: "APPROVE",
|
|
259
|
+
body: `${APPROVAL_MARKER}\nš¢ Mergelight found nothing that needs fixing in this commit.`,
|
|
260
|
+
});
|
|
261
|
+
return "approved";
|
|
262
|
+
}
|
|
263
|
+
const taken = dismissal.otherCommitsOnly ? standing.filter((r) => r.commit_id !== headSha) : standing;
|
|
264
|
+
for (const r of taken) {
|
|
265
|
+
await api.write("PUT", `pulls/${number}/reviews/${r.id}/dismissals`, { message: dismissal.why ?? "A newer Mergelight review found something to look at.", event: "DISMISS" });
|
|
266
|
+
}
|
|
267
|
+
return taken.length ? "dismissed" : "none";
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
log(`Couldn't update Mergelight's approval: ${err instanceof Error ? err.message : String(err)}`);
|
|
271
|
+
return "none";
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
export async function reviewThreads(api, number) {
|
|
275
|
+
const data = await api.graphql(`query($owner: String!, $repo: String!, $number: Int!) {
|
|
276
|
+
repository(owner: $owner, name: $repo) {
|
|
277
|
+
pullRequest(number: $number) {
|
|
278
|
+
reviewThreads(first: 100) {
|
|
279
|
+
nodes { id isResolved isOutdated resolvedBy { login } comments(first: 50) { nodes { databaseId body authorAssociation author { __typename } } } }
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}`, { owner: api.owner, repo: api.repo, number });
|
|
284
|
+
return data?.repository.pullRequest.reviewThreads.nodes ?? [];
|
|
285
|
+
}
|
|
286
|
+
export const resolveThread = (api, id) => api.graphql(`mutation($id: ID!) { resolveReviewThread(input: { threadId: $id }) { thread { id } } }`, { id }, true);
|
|
287
|
+
const unresolveThread = (api, id) => api.graphql(`mutation($id: ID!) { unresolveReviewThread(input: { threadId: $id }) { thread { id } } }`, { id }, true);
|
|
288
|
+
/**
|
|
289
|
+
* Brings inline comments in line with the threads: fixed or resolved ones get a
|
|
290
|
+
* checkmark and a dropdown, and reopened or returning ones go back to the
|
|
291
|
+
* original. Returns what counts as handled now, for the summary.
|
|
292
|
+
*/
|
|
293
|
+
async function settleThreads(api, review, log) {
|
|
294
|
+
const handled = new Map();
|
|
295
|
+
let resolved = 0;
|
|
296
|
+
let threads;
|
|
297
|
+
try {
|
|
298
|
+
threads = await reviewThreads(api, review.pr.number);
|
|
299
|
+
}
|
|
300
|
+
catch (err) {
|
|
301
|
+
log(`Couldn't read review threads: ${err.message}`);
|
|
302
|
+
return { handled, resolved };
|
|
303
|
+
}
|
|
304
|
+
const open = new Set(review.findings.map((f) => f.id));
|
|
305
|
+
const sha = review.pr.head_sha.slice(0, 7);
|
|
306
|
+
const canWrite = writeAccess(api);
|
|
307
|
+
const edit = (commentId, body) => api.write("PATCH", `pulls/comments/${commentId}`, { body }).catch((err) => log(`Couldn't update a comment: ${err.message}`));
|
|
308
|
+
for (const t of threads) {
|
|
309
|
+
const found = threadFinding(t);
|
|
310
|
+
if (!found)
|
|
311
|
+
continue;
|
|
312
|
+
const by = t.resolvedBy?.login ?? null;
|
|
313
|
+
const action = threadAction(t, open);
|
|
314
|
+
if (!action) {
|
|
315
|
+
const was = readClosed(found.body);
|
|
316
|
+
if (was)
|
|
317
|
+
handled.set(found.id, { how: was.how, by, sha: was.sha });
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (action.kind === "fixed") {
|
|
321
|
+
let isResolved = !action.resolve;
|
|
322
|
+
if (action.resolve) {
|
|
323
|
+
try {
|
|
324
|
+
await resolveThread(api, t.id);
|
|
325
|
+
isResolved = true;
|
|
326
|
+
resolved++;
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
// GitHub only lets a workflow token resolve threads with contents: write. The comment still says it's handled.
|
|
330
|
+
const hint = /not accessible by integration/i.test(err.message) ? "the workflow needs contents: write for that" : err.message;
|
|
331
|
+
log(`Couldn't mark a fixed thread resolved: ${hint}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
handled.set(found.id, { how: "fixed", sha });
|
|
335
|
+
await edit(found.commentId, closedBody(found.body, { how: "fixed", resolved: isResolved, sha }));
|
|
336
|
+
}
|
|
337
|
+
else if (action.kind === "resolved") {
|
|
338
|
+
// A workflow token sees a private org member as CONTRIBUTOR, so ask who can write instead of trusting the association.
|
|
339
|
+
if (!by || !(await canWrite(by)))
|
|
340
|
+
continue;
|
|
341
|
+
handled.set(found.id, { how: "resolved", by });
|
|
342
|
+
await edit(found.commentId, closedBody(found.body, { how: "resolved", resolved: true, by }));
|
|
343
|
+
}
|
|
344
|
+
else {
|
|
345
|
+
if (action.kind === "regressed" && action.unresolve) {
|
|
346
|
+
await unresolveThread(api, t.id).catch((err) => log(`Couldn't reopen a thread: ${err.message}`));
|
|
347
|
+
}
|
|
348
|
+
await edit(found.commentId, reopenedBody(found.body, action.kind === "reopened"));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return { handled, resolved };
|
|
352
|
+
}
|
|
353
|
+
/** A yellow check. A review that couldn't run also ends neutral, but an approval says nothing about that. */
|
|
354
|
+
export function isYellowCheck(check) {
|
|
355
|
+
return check.conclusion === "action_required" || (check.conclusion === "neutral" && Boolean(check.output.title?.startsWith(LIGHT.yellow.dot)));
|
|
356
|
+
}
|
|
357
|
+
/** The newest Mergelight check on a commit. */
|
|
358
|
+
export async function latestCheck(api, sha) {
|
|
359
|
+
const runs = await api.get(`commits/${sha}/check-runs?check_name=${CHECK_NAME}`);
|
|
360
|
+
return [...runs.check_runs].sort((a, b) => b.id - a.id)[0];
|
|
361
|
+
}
|
|
362
|
+
/** When someone approves a PR with a yellow check, it turns green. A blocked check (a bug to fix) stays red. */
|
|
363
|
+
export async function approveCheck(api, number, by, approvedSha) {
|
|
364
|
+
const pr = await api.get(`pulls/${number}`);
|
|
365
|
+
// An approval covers the commit the person looked at. Code pushed after it hasn't had its human yet.
|
|
366
|
+
if (approvedSha && approvedSha !== pr.head.sha)
|
|
367
|
+
return `${by} approved an earlier commit, so it doesn't turn the Mergelight check on the newest one green.`;
|
|
368
|
+
const latest = await latestCheck(api, pr.head.sha);
|
|
369
|
+
if (!latest)
|
|
370
|
+
return "No Mergelight check on this commit.";
|
|
371
|
+
if (!isYellowCheck(latest))
|
|
372
|
+
return `Mergelight check is ${latest.conclusion ?? "still running"}, nothing to approve.`;
|
|
373
|
+
// GitHub lets anyone who can read a repository leave an approving review. "Needs a human" means a
|
|
374
|
+
// human the team trusts with the code, so only someone who can push turns the check green.
|
|
375
|
+
if (!(await writeAccess(api)(by)))
|
|
376
|
+
return `${by} can't push to this repository, so their approval doesn't turn the Mergelight check green.`;
|
|
377
|
+
const body = {
|
|
378
|
+
conclusion: "success",
|
|
379
|
+
output: {
|
|
380
|
+
title: `š¢ Approved by ${by}`,
|
|
381
|
+
summary: `Approved by ${by} after the Mergelight review.\n\n${latest.output.summary ?? ""}`.slice(0, 65_000),
|
|
382
|
+
},
|
|
383
|
+
};
|
|
384
|
+
try {
|
|
385
|
+
await api.write("PATCH", `check-runs/${latest.id}`, body);
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
await api.write("POST", "check-runs", {
|
|
389
|
+
name: CHECK_NAME,
|
|
390
|
+
head_sha: pr.head.sha,
|
|
391
|
+
status: "completed",
|
|
392
|
+
completed_at: new Date().toISOString(),
|
|
393
|
+
...body,
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
return `Mergelight check approved by ${by}.`;
|
|
397
|
+
}
|