@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,82 @@
|
|
|
1
|
+
import { gunzipSync, gzipSync } from "node:zlib";
|
|
2
|
+
const MARKER = "mergelight:state:v1";
|
|
3
|
+
/** State shares a comment with the summary, and GitHub caps a comment at 65,536 characters. */
|
|
4
|
+
const MAX_STATE = 40_000;
|
|
5
|
+
const pack = (state) => `<!-- ${MARKER} ${gzipSync(JSON.stringify(state)).toString("base64")} -->`;
|
|
6
|
+
function withoutDetails(f) {
|
|
7
|
+
const { likelihood: _l, what_breaks: _w, fix: _f, fix_cost: _c, verdict: _v, rank: _r, ...rest } = f;
|
|
8
|
+
return rest;
|
|
9
|
+
}
|
|
10
|
+
function withoutHow(f) {
|
|
11
|
+
const { how: _, ...rest } = withoutDetails(f);
|
|
12
|
+
return rest;
|
|
13
|
+
}
|
|
14
|
+
/** Past any real review the details go first: a comment GitHub refuses would lose the whole round. */
|
|
15
|
+
export function encodeState(state) {
|
|
16
|
+
const packed = pack(state);
|
|
17
|
+
if (packed.length <= MAX_STATE)
|
|
18
|
+
return packed;
|
|
19
|
+
const slimmer = pack({ ...state, findings: state.findings.map(withoutDetails) });
|
|
20
|
+
return slimmer.length <= MAX_STATE ? slimmer : pack({ ...state, findings: state.findings.map(withoutHow) });
|
|
21
|
+
}
|
|
22
|
+
/** The encoded state exactly as it sits in a comment, to carry over into a new body. */
|
|
23
|
+
export function stateBlock(body) {
|
|
24
|
+
return body?.match(new RegExp(`<!-- ${MARKER} [A-Za-z0-9+/=]+ -->`))?.[0] ?? null;
|
|
25
|
+
}
|
|
26
|
+
export function decodeState(body) {
|
|
27
|
+
const m = body?.match(new RegExp(`<!-- ${MARKER} ([A-Za-z0-9+/=]+) -->`));
|
|
28
|
+
if (!m)
|
|
29
|
+
return null;
|
|
30
|
+
try {
|
|
31
|
+
const raw = Buffer.from(m[1], "base64");
|
|
32
|
+
// Reviews from before the state was gzipped are plain base64 JSON.
|
|
33
|
+
const json = raw[0] === 0x1f && raw[1] === 0x8b ? gunzipSync(raw, { maxOutputLength: 5_000_000 }) : raw;
|
|
34
|
+
const state = JSON.parse(json.toString("utf8"));
|
|
35
|
+
return state.v === 1 ? state : null;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Merge this review into the previous state. */
|
|
42
|
+
export function nextState(prev, findings, sha, light, urls) {
|
|
43
|
+
const round = (prev?.round ?? 0) + 1;
|
|
44
|
+
const current = new Set(findings.map((f) => f.id));
|
|
45
|
+
const before = new Map((prev?.findings ?? []).map((f) => [f.id, f]));
|
|
46
|
+
const merged = findings.map((f) => {
|
|
47
|
+
const url = urls.get(f.id) ?? before.get(f.id)?.url;
|
|
48
|
+
return {
|
|
49
|
+
id: f.id,
|
|
50
|
+
tier: f.tier,
|
|
51
|
+
class: f.class,
|
|
52
|
+
severity: f.severity,
|
|
53
|
+
title: f.title,
|
|
54
|
+
file: f.file,
|
|
55
|
+
line: f.line,
|
|
56
|
+
end_line: f.end_line,
|
|
57
|
+
how: f.how_it_happens,
|
|
58
|
+
likelihood: f.likelihood,
|
|
59
|
+
what_breaks: f.what_breaks,
|
|
60
|
+
fix: f.fix,
|
|
61
|
+
fix_cost: f.fix_cost,
|
|
62
|
+
verdict: f.verdict,
|
|
63
|
+
rank: f.rank ?? null,
|
|
64
|
+
first_round: before.get(f.id)?.first_round ?? round,
|
|
65
|
+
status: "open",
|
|
66
|
+
...(url ? { url } : {}),
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
for (const old of prev?.findings ?? []) {
|
|
70
|
+
if (!current.has(old.id))
|
|
71
|
+
merged.push({ ...withoutDetails(old), status: "gone" });
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
v: 1,
|
|
75
|
+
round,
|
|
76
|
+
rounds: [
|
|
77
|
+
...(prev?.rounds ?? []).slice(-19),
|
|
78
|
+
{ sha, at: new Date().toISOString(), light, posted: findings.filter((f) => f.tier === "post").length },
|
|
79
|
+
],
|
|
80
|
+
findings: merged,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** A team's check shows on the pull request under a name of its own, next to the Mergelight check. */
|
|
2
|
+
export const teamCheckName = (name) => `Mergelight: ${name}`;
|
|
3
|
+
/** As code, so nothing in it is read as markup, a link or a mention. */
|
|
4
|
+
const code = (text) => `\`${text.replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, "?")}\``;
|
|
5
|
+
/**
|
|
6
|
+
* Plain text for a check on GitHub. These words come from the AI, which read a pull request someone
|
|
7
|
+
* else wrote, or from the team's server. Neither may post a link, a picture, a mention or markup
|
|
8
|
+
* under Mergelight's name. Short pieces between backticks stay code, which GitHub shows as it is.
|
|
9
|
+
*/
|
|
10
|
+
export function plain(text) {
|
|
11
|
+
return text
|
|
12
|
+
.split(/(`[^`\n]+`)/)
|
|
13
|
+
.map((part, i) => i % 2
|
|
14
|
+
? part
|
|
15
|
+
: part
|
|
16
|
+
.replace(/[\\`*_{}[\]()#+!|<>~&]/g, "\\$&")
|
|
17
|
+
// A zero-width space: the text reads the same, and GitHub no longer sees a mention or a link.
|
|
18
|
+
.replace(/@/g, "@\u200b")
|
|
19
|
+
.replace(/:\/\//g, ":\u200b//")
|
|
20
|
+
.replace(/\bwww\./gi, "www\u200b."))
|
|
21
|
+
.join("")
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
/** What GitHub shows for one check: its conclusion, a title, and the reasons. */
|
|
25
|
+
/**
|
|
26
|
+
* A team makes a check stop a merge by requiring it on GitHub, and GitHub lets a neutral check
|
|
27
|
+
* through. So only a real pass is a success: "couldn't tell" and "couldn't run" ask for a person,
|
|
28
|
+
* which a required check doesn't let through. Otherwise the author of a pull request could get past
|
|
29
|
+
* a check by making its run fail.
|
|
30
|
+
*/
|
|
31
|
+
export function teamCheckBody(r) {
|
|
32
|
+
const asked = `**The check:** ${code(r.text)}`;
|
|
33
|
+
if (r.outcome === "skipped")
|
|
34
|
+
return { conclusion: "skipped", output: { title: "Not needed: none of its files changed", summary: `${asked}\n\n${r.summary}` } };
|
|
35
|
+
if (r.outcome === "unsure") {
|
|
36
|
+
return { conclusion: "action_required", output: { title: "Couldn't tell: look at this one yourself", summary: `${asked}\n\n${plain(r.summary)}\n\nThis is not a pass. If your team requires this check, it holds the merge until a run can tell.` } };
|
|
37
|
+
}
|
|
38
|
+
if (r.outcome === "error") {
|
|
39
|
+
return { conclusion: "action_required", output: { title: "Couldn't run this check", summary: `${asked}\n\n${plain(r.summary)}\n\nThis is not a pass. If your team requires this check, it holds the merge. Run the review again, or push, to try once more.` } };
|
|
40
|
+
}
|
|
41
|
+
const problems = r.problems.map((p) => `- ${code(p.line ? `${p.file}:${p.line}` : p.file)} ${plain(p.note)}`);
|
|
42
|
+
return {
|
|
43
|
+
conclusion: r.outcome === "pass" ? "success" : "failure",
|
|
44
|
+
output: {
|
|
45
|
+
title: r.outcome === "pass" ? "Passed" : `Failed${r.problems.length ? `: ${r.problems.length} place${r.problems.length === 1 ? "" : "s"} to fix` : ""}`,
|
|
46
|
+
summary: [asked, "", plain(r.summary), ...(problems.length ? ["", ...problems] : [])].join("\n").slice(0, 60_000),
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Posts each of the team's checks as a check of its own on the commit. Returns how many were
|
|
52
|
+
* posted. One that can't be posted is logged and doesn't stop the others.
|
|
53
|
+
*/
|
|
54
|
+
export async function publishTeamChecks(api, headSha, results, log = () => { }) {
|
|
55
|
+
let posted = 0;
|
|
56
|
+
for (const r of results) {
|
|
57
|
+
try {
|
|
58
|
+
await api.write("POST", "check-runs", { name: teamCheckName(r.name), head_sha: headSha, status: "completed", completed_at: new Date().toISOString(), ...teamCheckBody(r) });
|
|
59
|
+
posted++;
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
const message = err.message;
|
|
63
|
+
// GitHub only lets Apps write checks, so a personal gh login can't post any of them.
|
|
64
|
+
if (/must authenticate via a GitHub App/i.test(message)) {
|
|
65
|
+
log("Skipped your team's checks: GitHub only lets a GitHub App write checks, not a personal gh login.");
|
|
66
|
+
return posted;
|
|
67
|
+
}
|
|
68
|
+
log(`Couldn't post your team's check "${r.name}": ${message}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return posted;
|
|
72
|
+
}
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
2
|
+
const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
3
|
+
const bold = paint("1");
|
|
4
|
+
const dim = paint("2");
|
|
5
|
+
const red = paint("31");
|
|
6
|
+
const yellow = paint("33");
|
|
7
|
+
const green = paint("32");
|
|
8
|
+
const LIGHT = {
|
|
9
|
+
red: { dot: "🔴", label: "Blocked", color: red },
|
|
10
|
+
yellow: { dot: "🟡", label: "Needs a human", color: yellow },
|
|
11
|
+
green: { dot: "🟢", label: "Safe to merge", color: green },
|
|
12
|
+
};
|
|
13
|
+
function duration(ms) {
|
|
14
|
+
const s = Math.round(ms / 1000);
|
|
15
|
+
return s >= 60 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s` : `${s}s`;
|
|
16
|
+
}
|
|
17
|
+
function wrap(text, indent, width = 92) {
|
|
18
|
+
const words = text.replace(/\s+/g, " ").trim().split(" ");
|
|
19
|
+
const lines = [];
|
|
20
|
+
let line = "";
|
|
21
|
+
for (const w of words) {
|
|
22
|
+
if (line && (indent.length + line.length + 1 + w.length) > width) {
|
|
23
|
+
lines.push(line);
|
|
24
|
+
line = w;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
line = line ? `${line} ${w}` : w;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (line)
|
|
31
|
+
lines.push(line);
|
|
32
|
+
return lines.map((l, i) => (i === 0 ? l : indent + l)).join("\n");
|
|
33
|
+
}
|
|
34
|
+
function where(f) {
|
|
35
|
+
return f.end_line > f.line ? `${f.file}:${f.line}-${f.end_line}` : `${f.file}:${f.line}`;
|
|
36
|
+
}
|
|
37
|
+
function full(f, dot, label) {
|
|
38
|
+
const pad = " ";
|
|
39
|
+
return [
|
|
40
|
+
`${dot} ${bold(label)} ${bold(f.title)}`,
|
|
41
|
+
` ${dim(where(f))} ${dim(`${f.likelihood} · ${f.severity} · fix ${f.fix_cost}`)}`,
|
|
42
|
+
` How ${wrap(f.how_it_happens, pad)}`,
|
|
43
|
+
` Breaks ${wrap(f.what_breaks, pad)}`,
|
|
44
|
+
` Fix ${wrap(f.fix, pad)}`,
|
|
45
|
+
` ${bold(`→ ${f.verdict}`)}`,
|
|
46
|
+
].join("\n");
|
|
47
|
+
}
|
|
48
|
+
function kind(f) {
|
|
49
|
+
if (f.class === "bug")
|
|
50
|
+
return f.severity === "minor" ? { dot: "🟠", label: "Minor bug" } : { dot: "🔴", label: "Bug" };
|
|
51
|
+
if (f.class === "risk")
|
|
52
|
+
return { dot: "🟡", label: "Risk" };
|
|
53
|
+
return { dot: "⚪", label: "Small fix" };
|
|
54
|
+
}
|
|
55
|
+
export function renderTerminal(r) {
|
|
56
|
+
const light = LIGHT[r.light];
|
|
57
|
+
// Top picks first, most important first. Older reviews without picks post everything marked post.
|
|
58
|
+
const posted = r.findings.filter((f) => f.tier === "post").sort((a, b) => (a.rank ?? 9) - (b.rank ?? 9));
|
|
59
|
+
const listed = r.findings.filter((f) => f.tier === "list");
|
|
60
|
+
const decisions = r.findings.filter((f) => f.tier === "decision");
|
|
61
|
+
const hardening = r.findings.filter((f) => f.tier === "hardening");
|
|
62
|
+
const counts = [
|
|
63
|
+
`${posted.length} to fix first`,
|
|
64
|
+
`${listed.length} more worth fixing`,
|
|
65
|
+
`${decisions.length} decision${decisions.length === 1 ? "" : "s"}`,
|
|
66
|
+
`${hardening.length} hardening`,
|
|
67
|
+
].join(", ");
|
|
68
|
+
const words = (...parts) => parts.filter(Boolean).join(" ");
|
|
69
|
+
const hunters = words(r.provider.name, r.provider.model, r.provider.effort);
|
|
70
|
+
const checker = r.verifier && r.verifier.name !== r.provider.name ? `, checked by ${words(r.verifier.name, r.verifier.model)}` : "";
|
|
71
|
+
const out = [];
|
|
72
|
+
out.push(`${bold("Mergelight")} ${dim("·")} ${r.pr.owner}/${r.pr.repo}#${r.pr.number} ${dim("·")} ${r.pr.title}`);
|
|
73
|
+
out.push(`${light.dot} ${light.color(bold(light.label))} ${dim(`(${counts})`)} ${dim(`· ${hunters}${checker} · ${duration(r.stats.duration_ms)} · ${r.pr.head_sha.slice(0, 7)}`)}`);
|
|
74
|
+
const checked = r.trace.candidates.length;
|
|
75
|
+
out.push(dim(`Checked ${checked} candidate${checked === 1 ? "" : "s"}, rejected ${r.trace.rejected.length}${r.trace.failed_hunters.length ? `, hunters failed: ${r.trace.failed_hunters.join(", ")}` : ""}`));
|
|
76
|
+
out.push("");
|
|
77
|
+
out.push(wrap(r.summary, ""));
|
|
78
|
+
for (const f of posted) {
|
|
79
|
+
const k = kind(f);
|
|
80
|
+
out.push("", full(f, k.dot, k.label));
|
|
81
|
+
}
|
|
82
|
+
if (listed.length) {
|
|
83
|
+
out.push("", bold(`Also worth fixing (${listed.length})`));
|
|
84
|
+
for (const f of listed) {
|
|
85
|
+
out.push(` ${kind(f).dot} ${dim(where(f))} ${f.title}`);
|
|
86
|
+
out.push(` ${dim(`${f.likelihood} · ${f.severity} · fix ${f.fix_cost} ·`)} ${f.verdict}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (decisions.length) {
|
|
90
|
+
out.push("", bold(`Your call (${decisions.length})`));
|
|
91
|
+
for (const f of decisions) {
|
|
92
|
+
out.push(` ${dim(where(f))} ${f.title}`);
|
|
93
|
+
out.push(` ${dim(`${f.likelihood} · fix ${f.fix_cost} ·`)} ${f.verdict}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (hardening.length) {
|
|
97
|
+
out.push("", dim(`⚪ Hardening, not worth fixing by default (${hardening.length})`));
|
|
98
|
+
for (const f of hardening) {
|
|
99
|
+
out.push(dim(` ${where(f)} ${f.title}`));
|
|
100
|
+
out.push(dim(` → ${f.verdict}`));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!r.findings.length)
|
|
104
|
+
out.push("", green("Nothing worth fixing."));
|
|
105
|
+
if (r.team_checks?.length) {
|
|
106
|
+
out.push("", bold("Your team's checks"));
|
|
107
|
+
for (const c of r.team_checks) {
|
|
108
|
+
const mark = c.outcome === "pass" ? "✅" : c.outcome === "fail" ? "❌" : c.outcome === "skipped" ? "➖" : c.outcome === "unsure" ? "❔" : "⚠️";
|
|
109
|
+
out.push(` ${mark} ${c.name} ${dim(c.summary)}`);
|
|
110
|
+
for (const p of c.problems)
|
|
111
|
+
out.push(dim(` ${p.line ? `${p.file}:${p.line}` : p.file} ${p.note}`));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return out.join("\n");
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Each candidate the verifier threw out, with its reason. The review's own comment only keeps what was
|
|
118
|
+
* found, so this is how to answer "why wasn't X reported?". Printed only in debug runs: on a public
|
|
119
|
+
* repository the Action's log is public, and a wrongly rejected candidate can still be a real hole.
|
|
120
|
+
*/
|
|
121
|
+
export function renderRejected(r) {
|
|
122
|
+
return r.trace.rejected.map(({ candidate, reason }) => {
|
|
123
|
+
const number = /^C(\d+)$/.exec(candidate)?.[1];
|
|
124
|
+
const c = number ? r.trace.candidates[Number(number) - 1] : undefined;
|
|
125
|
+
// The verifier also rejects earlier rounds' findings, by their own ids.
|
|
126
|
+
const what = c ? `${c.title} (${c.file}:${c.line}, ${c.focus})` : number ? "a candidate the review didn't list" : "an earlier finding";
|
|
127
|
+
return `Rejected ${candidate}: ${what}. Why: ${reason}`;
|
|
128
|
+
});
|
|
129
|
+
}
|
package/dist/review.js
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { actionsUsedBy, fetchActionSources, notRead } from "./action-source.js";
|
|
5
|
+
import { fetchPullRequest } from "./github.js";
|
|
6
|
+
import { buildCheckPrompt, buildHunterPrompt, buildSweepPrompt, buildVerifierPrompt, focusesFor, ruleApplies, usedMemories, } from "./prompt.js";
|
|
7
|
+
import { LimitError, LoginError } from "./providers/codex.js";
|
|
8
|
+
import { claudeAvailable, runModel, TOOLING } from "./providers/index.js";
|
|
9
|
+
import { candidateSchema, checkSchema, reviewSchema, reviewSchemaWithDecisions } from "./schema.js";
|
|
10
|
+
import { CHECK_TIMEOUT_MS, startTeamChecks } from "./checks.js";
|
|
11
|
+
import { run } from "./run.js";
|
|
12
|
+
import { cacheDir, prepareWorkspace } from "./workspace.js";
|
|
13
|
+
/**
|
|
14
|
+
* Stable id for a finding: the file plus the code it points at, ignoring
|
|
15
|
+
* whitespace. It survives line shifts, so later review rounds can tell an old
|
|
16
|
+
* finding from a new one.
|
|
17
|
+
*/
|
|
18
|
+
function fingerprint(dir, f) {
|
|
19
|
+
let code = "";
|
|
20
|
+
try {
|
|
21
|
+
const lines = readFileSync(join(dir, f.file), "utf8").split("\n");
|
|
22
|
+
const start = Math.max(1, Math.min(f.line, f.end_line));
|
|
23
|
+
const end = Math.min(lines.length, Math.max(f.line, f.end_line), start + 30);
|
|
24
|
+
code = lines.slice(start - 1, end).join("\n").replace(/\s+/g, " ").trim();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
code = f.title.toLowerCase();
|
|
28
|
+
}
|
|
29
|
+
return createHash("sha1").update(`${f.file}\n${f.class}\n${code}`).digest("hex").slice(0, 10);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Gives each finding its id. One the verifier matched to an earlier round keeps
|
|
33
|
+
* that round's id and title, so it stays one comment however the model words or
|
|
34
|
+
* locates it this time: a fingerprint alone changes whenever the model cites
|
|
35
|
+
* slightly different lines.
|
|
36
|
+
*/
|
|
37
|
+
export function assignIds(findings, previous, fingerprintOf) {
|
|
38
|
+
const known = new Map(previous.map((p) => [p.id, p]));
|
|
39
|
+
const used = new Set();
|
|
40
|
+
const matched = findings.map((f) => {
|
|
41
|
+
const prior = f.same_as && !used.has(f.same_as) ? known.get(f.same_as) : undefined;
|
|
42
|
+
if (prior)
|
|
43
|
+
used.add(prior.id);
|
|
44
|
+
return prior;
|
|
45
|
+
});
|
|
46
|
+
return findings.map(({ same_as: _, ...f }, i) => {
|
|
47
|
+
const prior = matched[i];
|
|
48
|
+
if (prior)
|
|
49
|
+
return { ...f, id: prior.id, title: prior.title };
|
|
50
|
+
let id = fingerprintOf(f);
|
|
51
|
+
// Two findings on the same code still need their own ids.
|
|
52
|
+
for (let n = 1; used.has(id); n++)
|
|
53
|
+
id = createHash("sha1").update(`${id}${n}`).digest("hex").slice(0, 10);
|
|
54
|
+
used.add(id);
|
|
55
|
+
return { ...f, id };
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Only the verifier's top picks (at most 3 per PR) get their own comment. Other
|
|
60
|
+
* findings it says to fix are listed in the summary, decide becomes a "your
|
|
61
|
+
* call" line and leave is collapsed. In the eval, among problems only Mergelight
|
|
62
|
+
* raised, teams fixed 38% of Opus's top picks and 14% of its other findings.
|
|
63
|
+
* Posting everything it would fix meant about 4.5 comments per PR, and all of
|
|
64
|
+
* Codex's about 6.
|
|
65
|
+
*/
|
|
66
|
+
export function tierOf(f) {
|
|
67
|
+
// Teams fixed few of these: 19% of minor risks and 10% of rare findings, against 45% of minor bugs. They stay
|
|
68
|
+
// readable in the collapsed section, and a major bug is never hidden, because it decides the red light.
|
|
69
|
+
const majorBug = f.class === "bug" && f.severity !== "minor";
|
|
70
|
+
if (!majorBug && ((f.class === "risk" && f.severity === "minor") || f.likelihood === "rare"))
|
|
71
|
+
return "hardening";
|
|
72
|
+
if (f.rank)
|
|
73
|
+
return "post";
|
|
74
|
+
if (f.recommendation === "fix")
|
|
75
|
+
return "list";
|
|
76
|
+
if (f.recommendation === "decide")
|
|
77
|
+
return "decision";
|
|
78
|
+
return "hardening";
|
|
79
|
+
}
|
|
80
|
+
/** Red if a major bug must be fixed, yellow if anything else is posted or needs a decision, green otherwise. */
|
|
81
|
+
export function mergeLight(findings) {
|
|
82
|
+
if (findings.some((f) => f.class === "bug" && f.severity !== "minor" && f.recommendation === "fix"))
|
|
83
|
+
return "red";
|
|
84
|
+
if (findings.some((f) => f.tier !== "hardening"))
|
|
85
|
+
return "yellow";
|
|
86
|
+
return "green";
|
|
87
|
+
}
|
|
88
|
+
/** Tests and docs aren't swept: missing tests are never reported, and docs rarely hold real problems. */
|
|
89
|
+
const SKIP_SWEEP = /(^|\/)(test|tests|__tests__|e2e|docs?)\/|\.(spec|test)\.[cm]?[jt]sx?$|\.(md|mdx|txt)$/i;
|
|
90
|
+
const SWEEP_CHUNK = 12;
|
|
91
|
+
const SWEEP_MAX_RUNS = 3;
|
|
92
|
+
function normalizePath(p) {
|
|
93
|
+
return p.replace(/^\.\//, "").replace(/^\/+/, "");
|
|
94
|
+
}
|
|
95
|
+
const ORDER = { bug: 0, risk: 1, hardening: 2 };
|
|
96
|
+
/**
|
|
97
|
+
* High, not the Codex default. In the eval, gpt-6.1-sol (whose own default is
|
|
98
|
+
* low) found 41 of 51 fixed problems at high, 32 at medium and 29 at low.
|
|
99
|
+
*/
|
|
100
|
+
export const DEFAULT_EFFORT = "high";
|
|
101
|
+
/** Tells the prompts which tools the agent has. Without a shell it can't run git diff, so a big diff goes into the checkout. */
|
|
102
|
+
function forProvider(dir, input, provider) {
|
|
103
|
+
const tooling = TOOLING[provider];
|
|
104
|
+
if (tooling !== "files" || !input.diffTruncated)
|
|
105
|
+
return { ...input, tooling };
|
|
106
|
+
const diffFile = ".mergelight/pr.diff";
|
|
107
|
+
mkdirSync(join(dir, ".mergelight"), { recursive: true });
|
|
108
|
+
writeFileSync(join(dir, diffFile), input.diff);
|
|
109
|
+
return { ...input, tooling, diffFile };
|
|
110
|
+
}
|
|
111
|
+
/** The diff one of the team's checks reads: at most this much of it goes into the question. */
|
|
112
|
+
const MAX_CHECK_DIFF = 150_000;
|
|
113
|
+
/**
|
|
114
|
+
* The whole change to the files a check is about. Unlike the reviewers' diff it leaves nothing out:
|
|
115
|
+
* a check that names a lockfile or a generated file must see what changed in it, removed lines included.
|
|
116
|
+
*/
|
|
117
|
+
async function checkDiff(dir, base, head, files) {
|
|
118
|
+
// The names come from git itself and go back to it as they are: never as options, never as patterns.
|
|
119
|
+
const r = await run("git", ["--literal-pathspecs", "-C", dir, "diff", "-U5", "--no-color", "--no-ext-diff", "--no-renames", `${base}...${head}`, "--", ...files.slice(0, 50)], { timeoutMs: 60_000 });
|
|
120
|
+
if (r.code !== 0)
|
|
121
|
+
return { text: "", cut: true, missing: true };
|
|
122
|
+
return r.stdout.length > MAX_CHECK_DIFF ? { text: r.stdout.slice(0, MAX_CHECK_DIFF), cut: true } : { text: r.stdout, cut: files.length > 50 };
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The verifier: tries to disprove every candidate, merges duplicates, rates the
|
|
126
|
+
* rest and picks the few that matter most. Exported so the eval can replay the
|
|
127
|
+
* same candidates through another model.
|
|
128
|
+
*/
|
|
129
|
+
export async function verifyCandidates(dir, input, found, opts) {
|
|
130
|
+
const result = await runModel(opts.provider, {
|
|
131
|
+
cwd: dir,
|
|
132
|
+
prompt: buildVerifierPrompt(forProvider(dir, input, opts.provider), found),
|
|
133
|
+
// Only a verifier that was given the team's earlier decisions is asked which one it used.
|
|
134
|
+
schema: input.memories?.length ? reviewSchemaWithDecisions : reviewSchema,
|
|
135
|
+
model: opts.model,
|
|
136
|
+
effort: opts.effort,
|
|
137
|
+
logFile: opts.logFile,
|
|
138
|
+
onCommand: opts.onCommand,
|
|
139
|
+
});
|
|
140
|
+
const review = result.output;
|
|
141
|
+
const top = [...new Set((review.top ?? []).filter((n) => Number.isInteger(n) && n >= 1 && n <= review.findings.length))].slice(0, 3);
|
|
142
|
+
const findings = assignIds(review.findings, input.previous ?? [], (f) => fingerprint(dir, f))
|
|
143
|
+
.map((f, i) => {
|
|
144
|
+
const rank = top.includes(i + 1) ? top.indexOf(i + 1) + 1 : null;
|
|
145
|
+
return { ...f, tier: tierOf({ ...f, rank }), rank };
|
|
146
|
+
})
|
|
147
|
+
.sort((a, b) => ORDER[a.class] - ORDER[b.class] || a.file.localeCompare(b.file) || a.line - b.line);
|
|
148
|
+
return { summary: review.summary, findings, rejected: review.rejected, model: result.model, cost_usd: result.cost_usd ?? null };
|
|
149
|
+
}
|
|
150
|
+
/** Every rule a team can have for one repository: 50 for the org and 50 of its own. None is dropped. */
|
|
151
|
+
const MAX_RULES = 100;
|
|
152
|
+
/** The summary, with what the reader must know about the team's rules: a guarded file was changed, or the rules couldn't be read. */
|
|
153
|
+
export function summaryWith(summary, needsHuman, rulesUnread) {
|
|
154
|
+
// As code, so a name like __init__.py shows as it is and not as bold text.
|
|
155
|
+
const code = (path) => `\`${path.replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, "?")}\``;
|
|
156
|
+
const guarded = needsHuman.length
|
|
157
|
+
? ` It changes ${needsHuman.slice(0, 3).map(code).join(", ")}${needsHuman.length > 3 ? ` and ${needsHuman.length - 3} more` : ""}, which your team marked as always needing a human.`
|
|
158
|
+
: "";
|
|
159
|
+
// A team may have rules that would have changed this review. Running without them must never be silent.
|
|
160
|
+
const unread = rulesUnread ? " Mergelight couldn't get your team's rules, skills, checks and earlier decisions from its server, so this review ran without them." : "";
|
|
161
|
+
return `${summary}${guarded}${unread}`;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The light, with the team's "always needs a human" files taken into account. Such a file keeps a
|
|
165
|
+
* pull request from going green by itself. It never makes a light better: red stays red.
|
|
166
|
+
*/
|
|
167
|
+
export function lightWith(findings, needsHuman) {
|
|
168
|
+
const light = mergeLight(findings);
|
|
169
|
+
return light === "green" && needsHuman.length ? "yellow" : light;
|
|
170
|
+
}
|
|
171
|
+
/** The changed files that match a "needs a human" rule of the team. */
|
|
172
|
+
export function filesNeedingHuman(rules, changedFiles) {
|
|
173
|
+
const guards = (rules ?? []).filter((r) => r.kind === "needs_human" && r.paths?.length);
|
|
174
|
+
return changedFiles.filter((file) => guards.some((r) => ruleApplies(r, [file])));
|
|
175
|
+
}
|
|
176
|
+
/** Most recent first, as the server sends them. Enough for the files of one pull request, and not a wall of old decisions. */
|
|
177
|
+
const MAX_MEMORIES = 30;
|
|
178
|
+
/**
|
|
179
|
+
* A decision is about one problem in one file, so only those in files this pull request changes are
|
|
180
|
+
* passed on. One made on this very pull request is left out: the verifier already gets it with the
|
|
181
|
+
* earlier rounds, and reviewing its own pull request again must not count as a use that keeps it alive.
|
|
182
|
+
*/
|
|
183
|
+
export function memoriesFor(memories, changedFiles, pullRequest) {
|
|
184
|
+
// The same file, however its path was written down: src/a.ts, ./src/a.ts or /src/a.ts.
|
|
185
|
+
const plain = (path) => path.replace(/^(\.\/|\/)+/, "");
|
|
186
|
+
const changed = new Set(changedFiles.map(plain));
|
|
187
|
+
return (memories ?? []).filter((m) => changed.has(plain(m.file)) && m.pr !== pullRequest).slice(0, MAX_MEMORIES);
|
|
188
|
+
}
|
|
189
|
+
export async function reviewPullRequest(ref, opts = {}) {
|
|
190
|
+
const started = Date.now();
|
|
191
|
+
const progress = opts.onProgress ?? (() => { });
|
|
192
|
+
const effort = opts.effort ?? DEFAULT_EFFORT;
|
|
193
|
+
const provider = opts.provider ?? "codex";
|
|
194
|
+
const hunterModel = provider === "claude" ? (opts.model ?? "opus") : opts.model;
|
|
195
|
+
progress(`Reading ${ref.owner}/${ref.repo}#${ref.number}`);
|
|
196
|
+
const pr = await fetchPullRequest(ref);
|
|
197
|
+
progress("Checking out the code");
|
|
198
|
+
const ws = await prepareWorkspace(pr, opts.at, opts.skills);
|
|
199
|
+
const skillsMissing = (opts.skills?.length ?? 0) - ws.skills.length;
|
|
200
|
+
if (skillsMissing > 0)
|
|
201
|
+
progress(`${skillsMissing} of the skill folders your team picked ${skillsMissing === 1 ? "has" : "have"} no SKILL.md on the base branch, or couldn't be read: left out. Name the real folder, not a link to it`);
|
|
202
|
+
if (ws.skills.length)
|
|
203
|
+
progress(`Using your team's skill${ws.skills.length === 1 ? "" : "s"}: ${ws.skills.map((s) => s.name).join(", ")}`);
|
|
204
|
+
if (ws.conventions.length)
|
|
205
|
+
progress(`Using ${ws.conventions.map((c) => c.path).join(", ")} from ${pr.baseRef}`);
|
|
206
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
207
|
+
const log = (step) => join(cacheDir(), "logs", `${pr.owner}-${pr.repo}-${pr.number}-${stamp}-${step}.log`);
|
|
208
|
+
let checksRun = null;
|
|
209
|
+
try {
|
|
210
|
+
const input = {
|
|
211
|
+
pr,
|
|
212
|
+
mergeBase: ws.mergeBase,
|
|
213
|
+
headSha: ws.headSha,
|
|
214
|
+
diffStat: ws.diffStat,
|
|
215
|
+
diff: ws.diff,
|
|
216
|
+
diffTruncated: ws.diffTruncated,
|
|
217
|
+
previous: opts.previous,
|
|
218
|
+
memories: memoriesFor(opts.memories, ws.changedFiles.map((f) => f.path), pr.number),
|
|
219
|
+
// Matched against every path the pull request touches, exactly as git has it.
|
|
220
|
+
skills: ws.skills,
|
|
221
|
+
conventions: ws.conventions,
|
|
222
|
+
rules: (opts.rules ?? []).filter((r) => r.kind === "rule" && ruleApplies(r, ws.touchedPaths)).slice(0, MAX_RULES),
|
|
223
|
+
};
|
|
224
|
+
// Step 1: hunters, one per area, in parallel. One failing doesn't sink the review.
|
|
225
|
+
const addedTo = ws.changedFiles.filter((f) => f.added > 0).map((f) => f.path);
|
|
226
|
+
const focuses = focusesFor(addedTo);
|
|
227
|
+
let unread = [];
|
|
228
|
+
if (focuses.includes("supply")) {
|
|
229
|
+
const uses = actionsUsedBy(ws.dir, addedTo);
|
|
230
|
+
if (uses.length)
|
|
231
|
+
progress("Reading the source of the actions these workflows use");
|
|
232
|
+
input.actionSources = await fetchActionSources(uses);
|
|
233
|
+
unread = notRead(input.actionSources);
|
|
234
|
+
}
|
|
235
|
+
let done = 0;
|
|
236
|
+
progress(`Hunting for problems (0 of ${focuses.length} areas done)`);
|
|
237
|
+
const hunts = await Promise.allSettled(focuses.map(async (focus) => {
|
|
238
|
+
const result = await runModel(provider, {
|
|
239
|
+
cwd: ws.dir,
|
|
240
|
+
prompt: buildHunterPrompt(forProvider(ws.dir, input, provider), focus),
|
|
241
|
+
schema: candidateSchema,
|
|
242
|
+
model: hunterModel,
|
|
243
|
+
effort,
|
|
244
|
+
logFile: log(`hunt-${focus}`),
|
|
245
|
+
});
|
|
246
|
+
done++;
|
|
247
|
+
progress(`Hunting for problems (${done} of ${focuses.length} areas done)`);
|
|
248
|
+
return { focus, candidates: result.output.candidates, model: result.model };
|
|
249
|
+
}));
|
|
250
|
+
const failed = focuses.filter((_, i) => hunts[i].status === "rejected");
|
|
251
|
+
if (failed.length === focuses.length) {
|
|
252
|
+
const reasons = hunts.map((h) => h.reason);
|
|
253
|
+
throw reasons.find((r) => r instanceof LoginError) ?? reasons.find((r) => r instanceof LimitError) ?? reasons[0];
|
|
254
|
+
}
|
|
255
|
+
const found = hunts.flatMap((h) => h.status === "fulfilled" ? h.value.candidates.map((c) => ({ ...c, focus: h.value.focus })) : []);
|
|
256
|
+
// Step 1b: sweep changed files no hunter reported anything in.
|
|
257
|
+
const covered = new Set(found.map((c) => normalizePath(c.file)));
|
|
258
|
+
const uncovered = ws.changedFiles
|
|
259
|
+
.filter((f) => f.added > 0 && !covered.has(f.path) && !SKIP_SWEEP.test(f.path))
|
|
260
|
+
.sort((a, b) => b.added - a.added)
|
|
261
|
+
.slice(0, SWEEP_CHUNK * SWEEP_MAX_RUNS)
|
|
262
|
+
.map((f) => f.path);
|
|
263
|
+
if (uncovered.length) {
|
|
264
|
+
const chunks = [];
|
|
265
|
+
for (let i = 0; i < uncovered.length; i += SWEEP_CHUNK)
|
|
266
|
+
chunks.push(uncovered.slice(i, i + SWEEP_CHUNK));
|
|
267
|
+
progress(`Sweeping ${uncovered.length} file${uncovered.length === 1 ? "" : "s"} the hunters didn't mention`);
|
|
268
|
+
const sweeps = await Promise.allSettled(chunks.map((files, i) => runModel(provider, {
|
|
269
|
+
cwd: ws.dir,
|
|
270
|
+
prompt: buildSweepPrompt(forProvider(ws.dir, input, provider), files),
|
|
271
|
+
schema: candidateSchema,
|
|
272
|
+
model: hunterModel,
|
|
273
|
+
effort,
|
|
274
|
+
logFile: log(`sweep-${i + 1}`),
|
|
275
|
+
})));
|
|
276
|
+
sweeps.forEach((s, i) => {
|
|
277
|
+
if (s.status === "fulfilled") {
|
|
278
|
+
for (const c of s.value.output.candidates)
|
|
279
|
+
found.push({ ...c, focus: "sweep" });
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
failed.push(`sweep-${i + 1}`);
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
// The team's own checks run next to the verifier. They never fail the review and never hold it up
|
|
287
|
+
// for long: each ends as an answer or as an error of its own.
|
|
288
|
+
const teamChecks = opts.checks?.length
|
|
289
|
+
? startTeamChecks(opts.checks, ws.touchedPaths, async (check, files) => (await runModel(provider, {
|
|
290
|
+
cwd: ws.dir,
|
|
291
|
+
prompt: buildCheckPrompt({ ...input, tooling: TOOLING[provider] }, check, files, await checkDiff(ws.dir, ws.mergeBase, ws.headSha, files)),
|
|
292
|
+
schema: checkSchema,
|
|
293
|
+
model: hunterModel,
|
|
294
|
+
effort,
|
|
295
|
+
logFile: log(`check-${check.id}`),
|
|
296
|
+
timeoutMs: CHECK_TIMEOUT_MS,
|
|
297
|
+
projectDocs: false,
|
|
298
|
+
})).output, progress)
|
|
299
|
+
: null;
|
|
300
|
+
checksRun = teamChecks;
|
|
301
|
+
// Step 2: the verifier tries to disprove each candidate and sorts the rest.
|
|
302
|
+
// Opus checks better than Codex: in the eval it posted a third less and kept the same finds.
|
|
303
|
+
const verifyWith = opts.verifyWith ?? (provider === "claude" || (await claudeAvailable()) ? "claude" : "codex");
|
|
304
|
+
if (!opts.verifyWith && verifyWith === "codex")
|
|
305
|
+
progress("Claude Code isn't installed, so Codex checks the findings");
|
|
306
|
+
progress(`Checking ${found.length} candidate${found.length === 1 ? "" : "s"}${verifyWith === "codex" ? "" : ` with ${verifyWith}`}`);
|
|
307
|
+
const verified = await verifyCandidates(ws.dir, input, found, {
|
|
308
|
+
provider: verifyWith,
|
|
309
|
+
model: verifyWith === "codex" ? (opts.verifyModel ?? opts.model) : (opts.verifyModel ?? "opus"),
|
|
310
|
+
effort,
|
|
311
|
+
logFile: log("verify"),
|
|
312
|
+
onCommand: (cmd) => progress(`Checking ${found.length} candidates: ${cmd.replace(/\s+/g, " ").slice(0, 80)}`, true),
|
|
313
|
+
});
|
|
314
|
+
// Every path the pull request touches counts here, the lockfiles and generated files the reviewers skip included.
|
|
315
|
+
const needsHuman = filesNeedingHuman(opts.rules, ws.touchedPaths);
|
|
316
|
+
const team_checks = teamChecks ? await teamChecks.done : null;
|
|
317
|
+
const firstHunt = hunts.find((h) => h.status === "fulfilled");
|
|
318
|
+
const servedModel = firstHunt?.status === "fulfilled" ? firstHunt.value.model : null;
|
|
319
|
+
return {
|
|
320
|
+
schema_version: 1,
|
|
321
|
+
pr: {
|
|
322
|
+
owner: pr.owner,
|
|
323
|
+
repo: pr.repo,
|
|
324
|
+
number: pr.number,
|
|
325
|
+
title: pr.title,
|
|
326
|
+
url: pr.url,
|
|
327
|
+
base_sha: ws.mergeBase,
|
|
328
|
+
head_sha: ws.headSha,
|
|
329
|
+
},
|
|
330
|
+
provider: { name: provider, model: servedModel, effort },
|
|
331
|
+
verifier: { name: verifyWith, model: verified.model, effort, cost_usd: verified.cost_usd },
|
|
332
|
+
light: lightWith(verified.findings, needsHuman),
|
|
333
|
+
summary: summaryWith(verified.summary, needsHuman, opts.rulesUnread === true),
|
|
334
|
+
...(needsHuman.length ? { needs_human: needsHuman } : {}),
|
|
335
|
+
findings: verified.findings,
|
|
336
|
+
...(input.memories?.length ? { used_memories: usedMemories(input.memories, verified.rejected, found) } : {}),
|
|
337
|
+
...(team_checks?.length ? { team_checks } : {}),
|
|
338
|
+
...(unread.length ? { not_read: unread } : {}),
|
|
339
|
+
stats: {
|
|
340
|
+
duration_ms: Date.now() - started,
|
|
341
|
+
diff_chars: ws.diff.length,
|
|
342
|
+
files_changed: pr.changedFiles,
|
|
343
|
+
additions: pr.additions,
|
|
344
|
+
deletions: pr.deletions,
|
|
345
|
+
},
|
|
346
|
+
trace: {
|
|
347
|
+
candidates: found,
|
|
348
|
+
rejected: verified.rejected,
|
|
349
|
+
failed_hunters: failed,
|
|
350
|
+
},
|
|
351
|
+
created_at: new Date().toISOString(),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
finally {
|
|
355
|
+
// The checkout is about to go. A check that is still waiting for its turn must not start in it.
|
|
356
|
+
// What the checks answered so far goes to the caller, whether the review worked or not.
|
|
357
|
+
if (checksRun) {
|
|
358
|
+
checksRun.stop();
|
|
359
|
+
opts.onTeamChecks?.(await checksRun.done);
|
|
360
|
+
}
|
|
361
|
+
if (opts.keep)
|
|
362
|
+
progress(`Kept the checkout at ${ws.dir}`);
|
|
363
|
+
else
|
|
364
|
+
await ws.cleanup();
|
|
365
|
+
}
|
|
366
|
+
}
|