@mergelight/cli 0.1.14 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/checks.js +108 -0
- package/dist/cli.js +67 -7
- package/dist/cloud.js +383 -0
- package/dist/mcp/findings.js +5 -0
- package/dist/prompt.js +258 -5
- package/dist/providers/codex.js +26 -0
- package/dist/publish/closed.js +58 -0
- package/dist/publish/handled.js +22 -4
- package/dist/publish/markdown.js +3 -1
- package/dist/publish/publish.js +184 -29
- package/dist/publish/state.js +7 -3
- package/dist/publish/team-checks.js +72 -0
- package/dist/render.js +23 -0
- package/dist/review.js +102 -6
- package/dist/schema.js +49 -0
- package/dist/skills.js +177 -0
- package/dist/workspace.js +193 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -62,12 +62,12 @@ Other ways to name the pull request: `owner/repo#123`, or just `123` inside a cl
|
|
|
62
62
|
| `--keep` | Keep the temporary checkout |
|
|
63
63
|
| `--post` | Post the review to the PR: inline findings, one summary comment and a **Mergelight** check. GitHub only lets Apps write checks, so a personal `gh` login gets the comments and no check. The [GitHub Action](https://github.com/mergelightai/mergelight/blob/main/docs/github-action.md) gets all three |
|
|
64
64
|
| `--dry-run` | With `--post`, `post` or `approve`: print what would be posted and change nothing |
|
|
65
|
-
| `--yellow-blocks` | With `--post` or `post`: a 🟡 check waits for an approval instead of being neutral |
|
|
65
|
+
| `--yellow-blocks` | With `--post` or `post`: a 🟡 check waits for an approval and a 🔴 one fails, instead of both being neutral |
|
|
66
66
|
|
|
67
67
|
Two more commands, used by the GitHub Action:
|
|
68
68
|
|
|
69
69
|
- `mergelight post review.json` posts a review saved with `--out`.
|
|
70
|
-
- `mergelight approve owner/repo#123 --by login` turns a 🟡 "needs a human" check green after someone approves the PR. A 🔴 check stays
|
|
70
|
+
- `mergelight approve owner/repo#123 --by login` turns a 🟡 "needs a human" check green after someone approves the PR. A 🔴 "blocked" check stays blocked until a fix.
|
|
71
71
|
|
|
72
72
|
`mergelight init` adds Mergelight to your coding agents, and `mergelight mcp` is the MCP server they start, so Claude Code, Codex or Cursor can read a PR's findings and mark them handled. `mergelight setup owner/repo` sets up the GitHub Action from a terminal.
|
|
73
73
|
|
package/dist/checks.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { matchesPath } from "./prompt.js";
|
|
2
|
+
/** A repository's checks that a review runs. Each one that applies is an AI run of its own. */
|
|
3
|
+
export const MAX_CHECKS = 5;
|
|
4
|
+
const MAX_PROBLEMS = 10;
|
|
5
|
+
/** How many of them ask the AI at the same time. */
|
|
6
|
+
const AT_ONCE = 2;
|
|
7
|
+
/** One check gets this long, and all of them together this long. A review never waits for its checks beyond that. */
|
|
8
|
+
export const CHECK_TIMEOUT_MS = 6 * 60_000;
|
|
9
|
+
export const ALL_CHECKS_TIMEOUT_MS = 12 * 60_000;
|
|
10
|
+
/** The changed files a check is about. None means the check has nothing to look at in this pull request. */
|
|
11
|
+
export function filesOf(check, touched) {
|
|
12
|
+
return touched.filter((file) => check.paths.some((pattern) => matchesPath(pattern, file)));
|
|
13
|
+
}
|
|
14
|
+
/** One line of the model's words, cut to size. Whatever it is, it ends up as text on GitHub. */
|
|
15
|
+
function words(value, max) {
|
|
16
|
+
return typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, max).trim() : "";
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Reads the model's answer to a check. An answer that isn't shaped right is no answer: the check
|
|
20
|
+
* then ends as an error, never as a pass.
|
|
21
|
+
*/
|
|
22
|
+
export function readAnswer(output) {
|
|
23
|
+
const o = output;
|
|
24
|
+
if (!o || typeof o !== "object" || (o.verdict !== "pass" && o.verdict !== "fail" && o.verdict !== "unsure"))
|
|
25
|
+
return null;
|
|
26
|
+
const summary = words(o.summary, 600);
|
|
27
|
+
if (!summary)
|
|
28
|
+
return null;
|
|
29
|
+
const problems = [];
|
|
30
|
+
if (o.verdict === "fail" && Array.isArray(o.problems)) {
|
|
31
|
+
for (const raw of o.problems.slice(0, MAX_PROBLEMS)) {
|
|
32
|
+
const p = raw;
|
|
33
|
+
const file = words(p?.file, 300);
|
|
34
|
+
const note = words(p?.note, 400);
|
|
35
|
+
if (!file || !note)
|
|
36
|
+
continue;
|
|
37
|
+
const line = typeof p?.line === "number" && Number.isSafeInteger(p.line) && p.line > 0 ? p.line : 0;
|
|
38
|
+
problems.push({ file, line, note });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { outcome: o.verdict, summary, problems };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Runs the team's checks on a pull request. ask puts one check to the AI and resolves with its
|
|
45
|
+
* answer. Nothing here throws, and nothing here outlasts its time: a check that can't be run, or
|
|
46
|
+
* that takes too long, ends as an error of its own, and the review it belongs to goes on.
|
|
47
|
+
*/
|
|
48
|
+
export function startTeamChecks(checks, touched, ask, onProgress = () => { }, limits = { each: CHECK_TIMEOUT_MS, all: ALL_CHECKS_TIMEOUT_MS }) {
|
|
49
|
+
const list = checks.slice(0, MAX_CHECKS);
|
|
50
|
+
const results = new Array(list.length).fill(undefined);
|
|
51
|
+
const base = (check) => ({ id: check.id, name: check.name, text: check.text });
|
|
52
|
+
const skipped = (check) => ({ ...base(check), outcome: "skipped", summary: "This pull request changes none of the files this check is about.", problems: [] });
|
|
53
|
+
let over = null;
|
|
54
|
+
let finish = () => { };
|
|
55
|
+
const done = new Promise((resolve) => (finish = resolve));
|
|
56
|
+
const timer = setTimeout(() => end("This check took too long and was stopped."), limits.all);
|
|
57
|
+
timer.unref();
|
|
58
|
+
/** Closes the run with what there is. Whatever hasn't answered by now has no answer. */
|
|
59
|
+
function end(why) {
|
|
60
|
+
if (over !== null)
|
|
61
|
+
return;
|
|
62
|
+
over = why;
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
// A check that never got its turn and has no file to look at was never going to run.
|
|
65
|
+
finish(list.map((check, i) => results[i] ?? (filesOf(check, touched).length ? { ...base(check), outcome: "error", summary: why, problems: [] } : skipped(check))));
|
|
66
|
+
}
|
|
67
|
+
let next = 0;
|
|
68
|
+
const worker = async () => {
|
|
69
|
+
for (;;) {
|
|
70
|
+
if (over !== null)
|
|
71
|
+
return;
|
|
72
|
+
const index = next++;
|
|
73
|
+
const check = list[index];
|
|
74
|
+
if (!check)
|
|
75
|
+
return;
|
|
76
|
+
const files = filesOf(check, touched);
|
|
77
|
+
if (!files.length) {
|
|
78
|
+
results[index] = skipped(check);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
onProgress(`Running your team's check "${check.name}"`);
|
|
82
|
+
let result;
|
|
83
|
+
let tooLong;
|
|
84
|
+
try {
|
|
85
|
+
const late = new Promise((_, reject) => {
|
|
86
|
+
tooLong = setTimeout(() => reject(new Error("it took too long")), limits.each);
|
|
87
|
+
tooLong.unref();
|
|
88
|
+
});
|
|
89
|
+
const answer = readAnswer(await Promise.race([ask(check, files), late]));
|
|
90
|
+
result = answer ? { ...base(check), ...answer } : { ...base(check), outcome: "error", summary: "The AI's answer to this check couldn't be read.", problems: [] };
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
const reason = words(err instanceof Error ? err.message : String(err), 300);
|
|
94
|
+
result = { ...base(check), outcome: "error", summary: `The AI run for this check failed${reason ? `: ${reason}` : "."}`, problems: [] };
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
clearTimeout(tooLong);
|
|
98
|
+
}
|
|
99
|
+
// An answer that comes after the run was closed is not used: the review has moved on.
|
|
100
|
+
if (over !== null)
|
|
101
|
+
return;
|
|
102
|
+
results[index] = result;
|
|
103
|
+
onProgress(`Your team's check "${check.name}": ${{ pass: "passed", fail: "failed", unsure: "couldn't tell", skipped: "skipped", error: "couldn't run" }[result.outcome]}`);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
void Promise.all(Array.from({ length: Math.min(AT_ONCE, list.length) }, worker)).then(() => end("This check didn't finish."));
|
|
107
|
+
return { done, stop: () => end("The review ended before this check answered.") };
|
|
108
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -3,11 +3,14 @@ import { readFileSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { currentRepo, fetchPullRequest, parsePrRef } from "./github.js";
|
|
5
5
|
import { serve } from "./mcp/server.js";
|
|
6
|
+
import { declinesOf, fetchContext, MAX_REASON, reportReview } from "./cloud.js";
|
|
6
7
|
import { GitHub } from "./publish/api.js";
|
|
7
|
-
import {
|
|
8
|
+
import { writeAccess } from "./publish/handled.js";
|
|
9
|
+
import { publishTeamChecks } from "./publish/team-checks.js";
|
|
10
|
+
import { answerRemembered, confirmReasons, approveCheck, checkLimitTitle, checkLoginTitle, failCheck, failSummary, previousFindings, publishReview, startCheck, startSummary, syncApproval, UNREVIEWED } from "./publish/publish.js";
|
|
8
11
|
import { LimitError, LoginError, loginFailureMessage } from "./providers/codex.js";
|
|
9
12
|
import { limitNotice, loginNotice } from "./publish/markdown.js";
|
|
10
|
-
import { renderTerminal } from "./render.js";
|
|
13
|
+
import { renderRejected, renderTerminal } from "./render.js";
|
|
11
14
|
import { reviewPullRequest } from "./review.js";
|
|
12
15
|
import { askForApp, connect, githubConnect } from "./connect.js";
|
|
13
16
|
import { init, realInitDeps } from "./init.js";
|
|
@@ -31,7 +34,7 @@ Options
|
|
|
31
34
|
--post Post the review to the PR: summary comment, inline findings, check
|
|
32
35
|
(the check needs a GitHub App, a personal gh login skips it)
|
|
33
36
|
--dry-run With --post, post or approve: print what would be posted, change nothing
|
|
34
|
-
--yellow-blocks With --post or post: a "needs a human" check waits for an approval
|
|
37
|
+
--yellow-blocks With --post or post: a "needs a human" check waits for an approval and a "blocked" one fails
|
|
35
38
|
--json Print the review as JSON
|
|
36
39
|
--out <file> Also write the JSON review to a file
|
|
37
40
|
--provider <name> Who hunts for problems: codex or claude (default: codex)
|
|
@@ -42,6 +45,7 @@ Options
|
|
|
42
45
|
--verify-model <name> Model for the checker (default for claude: opus)
|
|
43
46
|
--keep Keep the temporary checkout
|
|
44
47
|
--by <login> Who approved, for approve
|
|
48
|
+
With approve, --at is the commit they approved: an older one doesn't count
|
|
45
49
|
--base <branch> For setup: add the workflows to this branch (default: the default branch)
|
|
46
50
|
--skip-branches <a,b> For setup: don't review pull requests from these branches
|
|
47
51
|
--relogin For setup: log in to Codex again
|
|
@@ -193,7 +197,7 @@ async function main() {
|
|
|
193
197
|
log("approve needs --by <login>");
|
|
194
198
|
return 1;
|
|
195
199
|
}
|
|
196
|
-
log(await approveCheck(new GitHub(ref.owner, ref.repo, { dryRun, log }), ref.number, values.by));
|
|
200
|
+
log(await approveCheck(new GitHub(ref.owner, ref.repo, { dryRun, log }), ref.number, values.by, values.at || undefined));
|
|
197
201
|
return 0;
|
|
198
202
|
}
|
|
199
203
|
// review
|
|
@@ -205,14 +209,30 @@ async function main() {
|
|
|
205
209
|
checkRunId = await startCheck(api, headSha);
|
|
206
210
|
await startSummary(api, ref.number).catch((e) => log(`Couldn't post the summary yet: ${e.message}`));
|
|
207
211
|
}
|
|
212
|
+
// Teams that use the dashboard: ask the server first, so nothing is sent for anyone else.
|
|
213
|
+
const cloud = values.post && !dryRun ? await fetchContext({ log }) : { connected: false, memories: [], rules: [], skills: [], checks: [], writtenSkills: [] };
|
|
208
214
|
const progress = progressPrinter();
|
|
215
|
+
/** The team's checks that have an answer which isn't on GitHub yet. */
|
|
216
|
+
let answered;
|
|
217
|
+
let checksPosted = false;
|
|
209
218
|
try {
|
|
210
219
|
// The login step already found this login can't be refreshed, so don't send every reviewer to find out.
|
|
211
220
|
if (process.env.MERGELIGHT_LOGIN_LOST === "1")
|
|
212
221
|
throw new LoginError(loginFailureMessage(process.env.SECRET_NAME || undefined));
|
|
222
|
+
// Before the threads are read: a reply written after this counts as newer than this review.
|
|
223
|
+
const startedAt = new Date();
|
|
224
|
+
let previous = values.post ? await previousFindings(api, ref.number, headSha ?? undefined) : undefined;
|
|
213
225
|
const review = await reviewPullRequest(ref, {
|
|
214
|
-
previous
|
|
215
|
-
|
|
226
|
+
previous,
|
|
227
|
+
memories: cloud.memories,
|
|
228
|
+
rules: cloud.rules,
|
|
229
|
+
rulesUnread: cloud.failed === true,
|
|
230
|
+
skills: cloud.skills,
|
|
231
|
+
writtenSkills: cloud.writtenSkills,
|
|
232
|
+
checks: cloud.checks,
|
|
233
|
+
onTeamChecks: (results) => (answered = results),
|
|
234
|
+
// The commit the check and the earlier findings were read for, so a push in between doesn't mix two.
|
|
235
|
+
at: values.at ?? headSha ?? undefined,
|
|
216
236
|
provider,
|
|
217
237
|
model: values.model,
|
|
218
238
|
effort: values.effort,
|
|
@@ -226,9 +246,41 @@ async function main() {
|
|
|
226
246
|
if (values.out)
|
|
227
247
|
writeFileSync(values.out, `${json}\n`);
|
|
228
248
|
process.stdout.write(values.json ? `${json}\n` : `${renderTerminal(review)}\n`);
|
|
249
|
+
// GitHub sets RUNNER_DEBUG when someone re-runs a job with debug logging on.
|
|
250
|
+
if (process.env.RUNNER_DEBUG === "1" || process.env.MERGELIGHT_DEBUG === "1")
|
|
251
|
+
for (const line of renderRejected(review))
|
|
252
|
+
log(line);
|
|
229
253
|
if (values.post) {
|
|
230
|
-
|
|
254
|
+
previous = confirmReasons(previous, review.trace.rejected);
|
|
255
|
+
// Reasons given in threads that this review sends to keep: the state holds them until the server confirms.
|
|
256
|
+
// Also when the server couldn't be asked this time, so a waiting reason isn't dropped from the state.
|
|
257
|
+
const remember = cloud.connected || cloud.failed ? (previous ?? []).filter((p) => p.handled?.from === "reply" && p.handled.remember && p.handled.at).map((p) => ({ id: p.id, at: p.handled.at, tries: (p.handled.tries ?? 0) + (cloud.connected ? 1 : 0) })) : [];
|
|
258
|
+
const result = await publishReview(review, { dryRun, log, checkRunId, yellowBlocks: values["yellow-blocks"], teamUnread: cloud.failed === true, startedAt, remember });
|
|
231
259
|
log(`Posted: ${result.inline} inline, ${result.outside} in the summary only, ${result.resolved} resolved. ${result.summaryUrl ?? ""}`);
|
|
260
|
+
if (review.team_checks?.length) {
|
|
261
|
+
checksPosted = true;
|
|
262
|
+
const posted = await publishTeamChecks(api, review.pr.head_sha, review.team_checks, log).catch((e) => (log(`Couldn't post your team's checks: ${e.message}`), 0));
|
|
263
|
+
if (posted)
|
|
264
|
+
log(`Posted ${posted} of your team's check${posted === 1 ? "" : "s"}.`);
|
|
265
|
+
}
|
|
266
|
+
if (cloud.connected) {
|
|
267
|
+
// A decision is only remembered when GitHub says its author can push to this repository. Being a
|
|
268
|
+
// member of the org is not enough: this outlives the pull request it was made on.
|
|
269
|
+
const canWrite = writeAccess(api);
|
|
270
|
+
const declines = [];
|
|
271
|
+
for (const d of declinesOf(previous))
|
|
272
|
+
if (await canWrite(d.by))
|
|
273
|
+
declines.push(d);
|
|
274
|
+
const { remembered } = await reportReview(review, { log }, declines);
|
|
275
|
+
// A reason given in a thread gets an answer there, once the server says it kept it. A mark was
|
|
276
|
+
// written through the agent tools, which say so themselves.
|
|
277
|
+
const fromThreads = (previous ?? []).filter((p) => p.handled?.from === "reply" && p.handled.remember);
|
|
278
|
+
const cut = new Set(fromThreads.filter((p) => p.handled?.cut || (p.handled?.note?.length ?? 0) > MAX_REASON).map((p) => p.id));
|
|
279
|
+
const answer = (remembered ?? []).filter((id) => fromThreads.some((p) => p.id === id));
|
|
280
|
+
const answered = await answerRemembered(api, ref.number, answer, cut, log);
|
|
281
|
+
if (answered)
|
|
282
|
+
log(`Remembered ${answered} reason${answered === 1 ? "" : "s"} given in a thread, and said so there.`);
|
|
283
|
+
}
|
|
232
284
|
// The check carries the verdict; the job itself only fails on errors.
|
|
233
285
|
return 0;
|
|
234
286
|
}
|
|
@@ -245,6 +297,14 @@ async function main() {
|
|
|
245
297
|
const notice = limit ? limitNotice(limit.plan, limit.resets) : login ? loginNotice(login.plan, message) : undefined;
|
|
246
298
|
await failCheck(api, checkRunId, headSha, message, log, title).catch((e) => log(`Couldn't update the check: ${e.message}`));
|
|
247
299
|
await failSummary(api, ref.number, notice).catch((e) => log(`Couldn't update the summary: ${e.message}`));
|
|
300
|
+
// The newest commit wasn't reviewed. An approval Mergelight gave to an earlier commit must not count for this one.
|
|
301
|
+
await syncApproval(api, ref.number, "yellow", headSha, log, { why: UNREVIEWED, otherCommitsOnly: true });
|
|
302
|
+
// Each of the team's checks still gets an answer on GitHub, so a required one says why it holds the merge:
|
|
303
|
+
// the answer it already has, or that it wasn't asked.
|
|
304
|
+
const unasked = cloud.checks.map((c) => ({ id: c.id, name: c.name, text: c.text, outcome: "error", summary: "The review couldn't run, so this check wasn't asked.", problems: [] }));
|
|
305
|
+
const owed = checksPosted ? [] : (answered ?? unasked);
|
|
306
|
+
if (owed.length)
|
|
307
|
+
await publishTeamChecks(api, headSha, owed, log).catch((e) => log(`Couldn't post your team's checks: ${e.message}`));
|
|
248
308
|
}
|
|
249
309
|
return 1;
|
|
250
310
|
}
|
package/dist/cloud.js
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { isSkillPath, isSkillText, withoutHidden } from "./skills.js";
|
|
3
|
+
/**
|
|
4
|
+
* The Mergelight server, for teams that use the dashboard. Off unless MERGELIGHT_SERVER is set.
|
|
5
|
+
*
|
|
6
|
+
* This program talks to the server, before the reviewing model starts and after it has finished.
|
|
7
|
+
* The model never does: it has no network, no tool for it and no token.
|
|
8
|
+
*
|
|
9
|
+
* A run proves which repository it is with GitHub's OIDC token, so there is no key to store. Each
|
|
10
|
+
* token is made for the one server it goes to, so no other server accepts it, and it is used once.
|
|
11
|
+
*
|
|
12
|
+
* Whatever goes wrong here must not stop or change the review. A server that is down, slow or
|
|
13
|
+
* hostile costs a review a few seconds at most.
|
|
14
|
+
*/
|
|
15
|
+
/** Everything one question to the server may take: asking GitHub for tokens, both tries, and reading the answer. */
|
|
16
|
+
const DEADLINE_MS = 10_000;
|
|
17
|
+
/**
|
|
18
|
+
* The largest answer that is read. A team's full set of rules and decisions fits well inside it,
|
|
19
|
+
* so a team can't lose its rules by having many. Anything past it isn't an answer, and isn't read.
|
|
20
|
+
*/
|
|
21
|
+
const MAX_ANSWER = 512 * 1024;
|
|
22
|
+
/** The server checks a model's name against the same alphabet. */
|
|
23
|
+
const MODEL_NAME = /^[\w.:/@[\]-]{1,100}$/;
|
|
24
|
+
export function reviewNumbers(review) {
|
|
25
|
+
const n = (keep) => review.findings.filter(keep).length;
|
|
26
|
+
const model = review.provider.model;
|
|
27
|
+
return {
|
|
28
|
+
pr: review.pr.number,
|
|
29
|
+
sha: review.pr.head_sha,
|
|
30
|
+
light: review.light,
|
|
31
|
+
counts: { bug: n((f) => f.class === "bug"), risk: n((f) => f.class === "risk"), hardening: n((f) => f.class === "hardening") },
|
|
32
|
+
tiers: { post: n((f) => f.tier === "post"), list: n((f) => f.tier === "list"), decision: n((f) => f.tier === "decision") },
|
|
33
|
+
major: n((f) => f.severity === "major"),
|
|
34
|
+
provider: review.provider.name,
|
|
35
|
+
// A model name outside this plain alphabet isn't sent at all, so nothing typed into a setting can travel as text.
|
|
36
|
+
// The brackets are for names like "sonnet[1m]".
|
|
37
|
+
model: model && MODEL_NAME.test(model) ? model : null,
|
|
38
|
+
verifier: review.verifier?.name ?? null,
|
|
39
|
+
duration_ms: Math.round(review.stats.duration_ms),
|
|
40
|
+
files_changed: review.stats.files_changed,
|
|
41
|
+
additions: review.stats.additions,
|
|
42
|
+
deletions: review.stats.deletions,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** The server's address, or null when it's off. Plain http is only for a server on this machine. */
|
|
46
|
+
export function serverUrl(env) {
|
|
47
|
+
const raw = env.MERGELIGHT_SERVER?.trim();
|
|
48
|
+
if (!raw)
|
|
49
|
+
return null;
|
|
50
|
+
let url;
|
|
51
|
+
try {
|
|
52
|
+
url = new URL(raw);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
58
|
+
return url.protocol === "https:" || (url.protocol === "http:" && local) ? url : null;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Who the OIDC token is made for: the server's own address, with its path if it's mounted under one.
|
|
62
|
+
* Another Mergelight server refuses it, and so does the token server, so a token can't be passed on
|
|
63
|
+
* to get anything anywhere else.
|
|
64
|
+
*/
|
|
65
|
+
export function audienceFor(server) {
|
|
66
|
+
return server.origin + server.pathname.replace(/\/+$/, "");
|
|
67
|
+
}
|
|
68
|
+
function defaults(deps) {
|
|
69
|
+
const env = deps.env ?? process.env;
|
|
70
|
+
return {
|
|
71
|
+
env,
|
|
72
|
+
fetchImpl: deps.fetchImpl ?? fetch,
|
|
73
|
+
log: deps.log ?? (() => { }),
|
|
74
|
+
// To stderr, where GitHub reads commands too, so it never lands in the review's JSON on stdout.
|
|
75
|
+
mask: deps.mask ?? ((value) => void (env.GITHUB_ACTIONS === "true" && process.stderr.write(`::add-mask::${value}\n`))),
|
|
76
|
+
deadlineMs: deps.deadlineMs ?? DEADLINE_MS,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** A new OIDC token from GitHub. The server takes each one once, so every request asks for its own. */
|
|
80
|
+
async function oidcToken(d, server, signal) {
|
|
81
|
+
const { ACTIONS_ID_TOKEN_REQUEST_URL: at, ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer } = d.env;
|
|
82
|
+
if (!at || !bearer)
|
|
83
|
+
throw new Error('the workflow needs "id-token: write" in its permissions');
|
|
84
|
+
const url = new URL(at);
|
|
85
|
+
url.searchParams.set("audience", audienceFor(server));
|
|
86
|
+
const res = await d.fetchImpl(url, { headers: { authorization: `Bearer ${bearer}` }, signal });
|
|
87
|
+
if (!res.ok)
|
|
88
|
+
throw new Error(`GitHub answered ${res.status} for the OIDC token`);
|
|
89
|
+
const { value } = (await res.json());
|
|
90
|
+
if (!value)
|
|
91
|
+
throw new Error("GitHub returned no OIDC token");
|
|
92
|
+
d.mask(value);
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
/** Reads a small JSON answer. A larger one is dropped unread, so a server can't fill this process's memory. */
|
|
96
|
+
async function readAnswer(res) {
|
|
97
|
+
const reader = res.body?.getReader();
|
|
98
|
+
if (!reader)
|
|
99
|
+
return null;
|
|
100
|
+
const chunks = [];
|
|
101
|
+
let size = 0;
|
|
102
|
+
for (;;) {
|
|
103
|
+
const { done, value } = await reader.read();
|
|
104
|
+
if (done)
|
|
105
|
+
break;
|
|
106
|
+
size += value.length;
|
|
107
|
+
if (size > MAX_ANSWER) {
|
|
108
|
+
await reader.cancel().catch(() => { });
|
|
109
|
+
throw new Error("its answer is too large");
|
|
110
|
+
}
|
|
111
|
+
chunks.push(value);
|
|
112
|
+
}
|
|
113
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
114
|
+
}
|
|
115
|
+
const drop = (res) => res.body?.cancel().catch(() => { });
|
|
116
|
+
/** Keeps a path in the server's address, for a server mounted under one, like https://example.com/mergelight. */
|
|
117
|
+
export function endpoint(server, path) {
|
|
118
|
+
return new URL(server.pathname.replace(/\/+$/, "") + path, server.origin);
|
|
119
|
+
}
|
|
120
|
+
/** The server is off without a word when it isn't set. A setting that can't be used gets a line, or a typo would look like "on". */
|
|
121
|
+
function serverOrSay(d) {
|
|
122
|
+
const server = serverUrl(d.env);
|
|
123
|
+
if (!server && d.env.MERGELIGHT_SERVER?.trim())
|
|
124
|
+
d.log("The Mergelight server setting isn't an https:// address, so the server is off for this review.");
|
|
125
|
+
return server;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* One question to the server, tried twice, each try with its own token, all inside one deadline.
|
|
129
|
+
* A redirect is an error: the token is for this server and goes nowhere else.
|
|
130
|
+
*/
|
|
131
|
+
async function call(d, server, path, init) {
|
|
132
|
+
const signal = AbortSignal.timeout(d.deadlineMs);
|
|
133
|
+
const late = () => new Error(`no answer within ${Math.round(d.deadlineMs / 1000)} seconds`);
|
|
134
|
+
for (let attempt = 1;; attempt++) {
|
|
135
|
+
let res;
|
|
136
|
+
try {
|
|
137
|
+
res = await d.fetchImpl(endpoint(server, path), {
|
|
138
|
+
method: init.method,
|
|
139
|
+
headers: { authorization: `Bearer ${await oidcToken(d, server, signal)}`, ...(init.body ? { "content-type": "application/json" } : {}) },
|
|
140
|
+
body: init.body,
|
|
141
|
+
redirect: "error",
|
|
142
|
+
signal,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
if (signal.aborted)
|
|
147
|
+
throw late();
|
|
148
|
+
if (attempt === 2)
|
|
149
|
+
throw err;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (res.status >= 500 && attempt === 1) {
|
|
153
|
+
await drop(res);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (!res.ok) {
|
|
157
|
+
await drop(res);
|
|
158
|
+
return { status: res.status, ok: false, answer: null };
|
|
159
|
+
}
|
|
160
|
+
// The server took the request. An answer that can't be read isn't a reason to send it again.
|
|
161
|
+
try {
|
|
162
|
+
return { status: res.status, ok: true, answer: await readAnswer(res) };
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
throw signal.aborted ? late() : err;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const NOTHING = { connected: false, memories: [], rules: [], skills: [], checks: [], writtenSkills: [] };
|
|
170
|
+
/** One line of plain text: no line breaks and no control characters, so it can't pass for anything but itself. */
|
|
171
|
+
const isText = (v, max) => typeof v === "string" && v.length > 0 && v.length <= max && !/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/.test(v);
|
|
172
|
+
const isLine = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 10_000_000;
|
|
173
|
+
/**
|
|
174
|
+
* The server's memories, each field checked. They go into the verifier's prompt, so one that isn't
|
|
175
|
+
* shaped right is left out, however it got there.
|
|
176
|
+
*/
|
|
177
|
+
export function readMemories(value) {
|
|
178
|
+
if (!Array.isArray(value))
|
|
179
|
+
return [];
|
|
180
|
+
const memories = [];
|
|
181
|
+
for (const raw of value.slice(0, 200)) {
|
|
182
|
+
const m = raw;
|
|
183
|
+
if (!m || typeof m !== "object")
|
|
184
|
+
continue;
|
|
185
|
+
if (typeof m.id !== "string" || !/^M\d{1,12}$/.test(m.id) || !isText(m.title, 200) || !isText(m.file, 400) || !isLine(m.line) || !isText(m.reason, MAX_REASON))
|
|
186
|
+
continue;
|
|
187
|
+
if (typeof m.by !== "string" || !/^[\w.-]{1,100}(\[bot\])?$/.test(m.by) || !isLine(m.pr))
|
|
188
|
+
continue;
|
|
189
|
+
memories.push({ id: m.id, title: m.title, file: m.file, line: m.line, ...(isLine(m.end_line) ? { end_line: m.end_line } : {}), reason: m.reason, by: m.by, pr: m.pr });
|
|
190
|
+
}
|
|
191
|
+
return memories;
|
|
192
|
+
}
|
|
193
|
+
/** A pattern for file paths as the dashboard takes them: plain path characters and the wildcards * and ?. */
|
|
194
|
+
const isPattern = (v) => typeof v === "string" && /^[\w.@+\-/*?]{1,100}$/.test(v);
|
|
195
|
+
/**
|
|
196
|
+
* The team's rules, each field checked. A rule is an instruction to the reviewers by design, so its
|
|
197
|
+
* shape is held tight: one line of plain text, and patterns made of path characters only.
|
|
198
|
+
*/
|
|
199
|
+
/**
|
|
200
|
+
* The team's own checks, as the server sent them. One that isn't shaped right is left out: its name
|
|
201
|
+
* ends up in the name of a check on GitHub and its text in a prompt, so both are held to their shapes here too.
|
|
202
|
+
*/
|
|
203
|
+
export function readChecks(value) {
|
|
204
|
+
if (!Array.isArray(value))
|
|
205
|
+
return [];
|
|
206
|
+
const checks = [];
|
|
207
|
+
for (const raw of value.slice(0, 50)) {
|
|
208
|
+
if (checks.length === 5)
|
|
209
|
+
break;
|
|
210
|
+
const c = raw;
|
|
211
|
+
if (!c || typeof c !== "object")
|
|
212
|
+
continue;
|
|
213
|
+
if (typeof c.id !== "string" || !/^K\d{1,12}$/.test(c.id) || !isText(c.text, 500))
|
|
214
|
+
continue;
|
|
215
|
+
const checkText = withoutHidden(c.text);
|
|
216
|
+
if (!checkText.trim())
|
|
217
|
+
continue;
|
|
218
|
+
if (typeof c.name !== "string" || c.name.length > 40 || !/^[A-Za-z0-9](?:[A-Za-z0-9._-]| (?! ))*$/.test(c.name) || c.name.endsWith(" "))
|
|
219
|
+
continue;
|
|
220
|
+
if (!Array.isArray(c.paths) || c.paths.length < 1 || c.paths.length > 10 || !c.paths.every(isPattern))
|
|
221
|
+
continue;
|
|
222
|
+
if (checks.some((other) => other.name.toLowerCase() === c.name.toLowerCase()))
|
|
223
|
+
continue;
|
|
224
|
+
checks.push({ id: c.id, name: c.name, text: checkText, paths: c.paths });
|
|
225
|
+
}
|
|
226
|
+
return checks;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* The skills a team wrote on its dashboard, as the server sent them. One that isn't shaped right is
|
|
230
|
+
* left out: its name and description go into every prompt and its text into a file the reviewers read.
|
|
231
|
+
*/
|
|
232
|
+
export function readWrittenSkills(value) {
|
|
233
|
+
if (!Array.isArray(value))
|
|
234
|
+
return [];
|
|
235
|
+
const skills = [];
|
|
236
|
+
for (const raw of value.slice(0, 50)) {
|
|
237
|
+
if (skills.length === 10)
|
|
238
|
+
break;
|
|
239
|
+
const s = raw;
|
|
240
|
+
if (!s || typeof s !== "object")
|
|
241
|
+
continue;
|
|
242
|
+
// What a person can't see is taken out, so the reviewers read what the team read on its dashboard.
|
|
243
|
+
const description = typeof s.description === "string" ? withoutHidden(s.description) : s.description;
|
|
244
|
+
const text = typeof s.text === "string" ? withoutHidden(s.text) : s.text;
|
|
245
|
+
if (typeof s.id !== "string" || !/^S\d{1,12}$/.test(s.id) || !isText(description, 300) || !isSkillText(text))
|
|
246
|
+
continue;
|
|
247
|
+
if (typeof s.name !== "string" || s.name.length > 40 || !/^[A-Za-z0-9](?:[A-Za-z0-9._-]| (?! ))*$/.test(s.name) || s.name.endsWith(" "))
|
|
248
|
+
continue;
|
|
249
|
+
if (skills.some((other) => other.name.toLowerCase() === s.name.toLowerCase()))
|
|
250
|
+
continue;
|
|
251
|
+
skills.push({ id: s.id, name: s.name, description, text });
|
|
252
|
+
}
|
|
253
|
+
return skills;
|
|
254
|
+
}
|
|
255
|
+
export function readRules(value) {
|
|
256
|
+
if (!Array.isArray(value))
|
|
257
|
+
return [];
|
|
258
|
+
const rules = [];
|
|
259
|
+
for (const raw of value.slice(0, 100)) {
|
|
260
|
+
const r = raw;
|
|
261
|
+
if (!r || typeof r !== "object")
|
|
262
|
+
continue;
|
|
263
|
+
if (typeof r.id !== "string" || !/^R\d{1,12}$/.test(r.id) || !isText(r.text, 300))
|
|
264
|
+
continue;
|
|
265
|
+
// A rule is never dropped for a character a person can't see: that character is taken out, and the rule stays.
|
|
266
|
+
const ruleText = withoutHidden(r.text);
|
|
267
|
+
if (!ruleText.trim())
|
|
268
|
+
continue;
|
|
269
|
+
if ((r.kind !== "rule" && r.kind !== "needs_human") || (r.scope !== "org" && r.scope !== "repo"))
|
|
270
|
+
continue;
|
|
271
|
+
const paths = r.paths === undefined || r.paths === null ? [] : r.paths;
|
|
272
|
+
if (!Array.isArray(paths) || paths.length > 10 || !paths.every(isPattern))
|
|
273
|
+
continue;
|
|
274
|
+
// "Always needs a human" is about files, so one that names none says nothing.
|
|
275
|
+
if (r.kind === "needs_human" && !paths.length)
|
|
276
|
+
continue;
|
|
277
|
+
rules.push({ id: r.id, kind: r.kind, text: ruleText, ...(paths.length ? { paths: paths } : {}), scope: r.scope });
|
|
278
|
+
}
|
|
279
|
+
return rules;
|
|
280
|
+
}
|
|
281
|
+
/** Asks the server what this review should know. Never throws: without an answer the review runs as it always has. */
|
|
282
|
+
export async function fetchContext(deps = {}) {
|
|
283
|
+
const d = defaults(deps);
|
|
284
|
+
const server = serverOrSay(d);
|
|
285
|
+
if (!server)
|
|
286
|
+
return NOTHING;
|
|
287
|
+
try {
|
|
288
|
+
const res = await call(d, server, "/v1/context", { method: "GET" });
|
|
289
|
+
if (!res.ok) {
|
|
290
|
+
d.log(`The Mergelight server answered ${res.status}. The review runs without it.`);
|
|
291
|
+
return { ...NOTHING, failed: true };
|
|
292
|
+
}
|
|
293
|
+
const answer = res.answer;
|
|
294
|
+
if (answer?.connected !== true)
|
|
295
|
+
return NOTHING;
|
|
296
|
+
const skills = Array.isArray(answer.skills) ? answer.skills.filter(isSkillPath).slice(0, 10) : [];
|
|
297
|
+
return { connected: true, memories: readMemories(answer.memories), rules: readRules(answer.rules), skills, checks: readChecks(answer.checks), writtenSkills: readWrittenSkills(answer.written_skills) };
|
|
298
|
+
}
|
|
299
|
+
catch (err) {
|
|
300
|
+
d.log(`Couldn't reach the Mergelight server (${err.message}). The review runs without it.`);
|
|
301
|
+
return { ...NOTHING, failed: true };
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** True when this repository's org uses the dashboard. */
|
|
305
|
+
export async function cloudConnected(deps = {}) {
|
|
306
|
+
return (await fetchContext(deps)).connected;
|
|
307
|
+
}
|
|
308
|
+
/** The server reads 64 KB per report. The decisions get most of it, and the numbers always fit beside them. */
|
|
309
|
+
const MAX_DECLINE_BYTES = 48_000;
|
|
310
|
+
/** The longest reason sent and read. The server refuses a longer one, and with it the whole report. */
|
|
311
|
+
export const MAX_REASON = 1000;
|
|
312
|
+
/**
|
|
313
|
+
* The decisions on this pull request that are worth remembering: someone wrote a mark that says
|
|
314
|
+
* "not fixing this" and gave a reason. A resolved thread has no reason, so it isn't one.
|
|
315
|
+
*/
|
|
316
|
+
export function declinesOf(previous) {
|
|
317
|
+
// Line breaks and control characters become spaces: a reason is one line of plain text by the time it is sent.
|
|
318
|
+
const clean = (text, max) => text.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]+/g, " ").replace(/ {2,}/g, " ").trim().slice(0, max).trim();
|
|
319
|
+
const declines = [];
|
|
320
|
+
// Reasons given in threads first: unlike marks, they aren't read again from the pull request each time.
|
|
321
|
+
const order = (p) => (p.handled?.from === "reply" ? 0 : 1);
|
|
322
|
+
for (const p of [...(previous ?? [])].sort((a, b) => order(a) - order(b))) {
|
|
323
|
+
const h = p.handled;
|
|
324
|
+
// A mark, or a reason someone just gave when they resolved the thread. A plain resolve has no reason to keep.
|
|
325
|
+
if (!h || h.as !== "wont_fix" || (h.from !== "mark" && !(h.from === "reply" && h.remember)) || !h.note?.trim())
|
|
326
|
+
continue;
|
|
327
|
+
if (!/^[a-f0-9]{6,40}$/.test(p.id) || !/^[\w.-]{1,100}(\[bot\])?$/.test(h.by) || !isLine(p.line))
|
|
328
|
+
continue;
|
|
329
|
+
const title = clean(p.title, 200);
|
|
330
|
+
const file = clean(p.file, 400);
|
|
331
|
+
// A person's own text, typed or pasted: characters nobody can see are taken out before anything reads it.
|
|
332
|
+
const reason = clean(withoutHidden(h.note), MAX_REASON);
|
|
333
|
+
const at = Date.parse(h.at ?? "");
|
|
334
|
+
if (!title || !file || !reason || !Number.isFinite(at))
|
|
335
|
+
continue;
|
|
336
|
+
declines.push({ finding_id: p.id, title, file, line: p.line, ...(isLine(p.end_line) ? { end_line: p.end_line } : {}), reason, by: h.by, decided_at: new Date(at).toISOString() });
|
|
337
|
+
}
|
|
338
|
+
// What fits one report, counted in bytes: a reason in another alphabet takes more of them than letters.
|
|
339
|
+
const fit = [];
|
|
340
|
+
let bytes = 0;
|
|
341
|
+
for (const d of declines.slice(0, 40)) {
|
|
342
|
+
bytes += Buffer.byteLength(JSON.stringify(d)) + 1;
|
|
343
|
+
if (bytes > MAX_DECLINE_BYTES)
|
|
344
|
+
break;
|
|
345
|
+
fit.push(d);
|
|
346
|
+
}
|
|
347
|
+
return fit;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Sends the review's numbers for the dashboard, with the team's new decisions to remember and the
|
|
351
|
+
* earlier ones this review used.
|
|
352
|
+
*/
|
|
353
|
+
export async function reportReview(review, deps = {}, declines = []) {
|
|
354
|
+
const d = defaults(deps);
|
|
355
|
+
const server = serverUrl(d.env);
|
|
356
|
+
if (!server)
|
|
357
|
+
return { stored: false, remembered: null };
|
|
358
|
+
try {
|
|
359
|
+
// One id for this report, the same on both tries, so the server keeps it once.
|
|
360
|
+
const used = (review.used_memories ?? []).filter((id) => /^M\d{1,12}$/.test(id)).slice(0, 200);
|
|
361
|
+
const body = JSON.stringify({ ...reviewNumbers(review), report_id: randomUUID(), ...(declines.length ? { declines } : {}), ...(used.length ? { used_memories: used } : {}) });
|
|
362
|
+
let res = await call(d, server, "/v1/reviews", { method: "POST", body });
|
|
363
|
+
if (res.status === 400 && declines.length) {
|
|
364
|
+
// The server refused something in the report. If it was a decision, the numbers still count: send
|
|
365
|
+
// them again without any. An older server, for one, takes shorter reasons than this version sends.
|
|
366
|
+
d.log("The Mergelight server refused the report with the team's decisions. Sending the numbers without them: the decisions aren't stored this time, and the next review of this pull request sends them again.");
|
|
367
|
+
declines = [];
|
|
368
|
+
res = await call(d, server, "/v1/reviews", { method: "POST", body: JSON.stringify({ ...JSON.parse(body), declines: undefined, report_id: randomUUID() }) });
|
|
369
|
+
}
|
|
370
|
+
d.log(res.ok ? "Sent this review's numbers to the Mergelight server." : `The Mergelight server answered ${res.status} to the review's numbers. The review itself is posted.`);
|
|
371
|
+
if (!res.ok)
|
|
372
|
+
return { stored: false, remembered: null };
|
|
373
|
+
const said = res.answer?.remembered;
|
|
374
|
+
const sent = new Set(declines.map((x) => x.finding_id));
|
|
375
|
+
// Only ids this report sent: the answer can't make Mergelight speak about any other finding.
|
|
376
|
+
const remembered = Array.isArray(said) ? said.filter((id) => typeof id === "string" && sent.has(id)) : null;
|
|
377
|
+
return { stored: true, remembered };
|
|
378
|
+
}
|
|
379
|
+
catch (err) {
|
|
380
|
+
d.log(`Couldn't send the review's numbers to the Mergelight server (${err.message}). The review itself is posted.`);
|
|
381
|
+
return { stored: false, remembered: null };
|
|
382
|
+
}
|
|
383
|
+
}
|
package/dist/mcp/findings.js
CHANGED
|
@@ -177,6 +177,11 @@ export async function markHandled(args) {
|
|
|
177
177
|
const unknown = args.ids.filter((id) => !known.has(id));
|
|
178
178
|
if (unknown.length)
|
|
179
179
|
throw new Error(`Not findings on this pull request: ${unknown.join(", ")}. Nothing was marked. list_findings has the ids.`);
|
|
180
|
+
// The review only counts marks by people who can push. Say so now, not after a mark that never counts.
|
|
181
|
+
const access = await api.get(`/repos/${ref.owner}/${ref.repo}`).catch(() => null);
|
|
182
|
+
if (access?.permissions?.push === false) {
|
|
183
|
+
throw new Error(`Nothing was marked: your GitHub login can't push to ${ref.owner}/${ref.repo}, and the review only counts marks by people who can. Ask someone who can push to mark it.`);
|
|
184
|
+
}
|
|
180
185
|
const reviewed = state.rounds.at(-1)?.sha;
|
|
181
186
|
if (as === "fixed" && reviewed === pr.headSha) {
|
|
182
187
|
throw new Error(`Nothing was marked: GitHub shows ${pr.headSha.slice(0, 7)} as the latest commit, and the latest review already looked at it. Push the fix first. If you just pushed, GitHub can take a few seconds to catch up, so try again.`);
|