@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
package/dist/cli.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { currentRepo, fetchPullRequest, parsePrRef } from "./github.js";
|
|
5
|
+
import { serve } from "./mcp/server.js";
|
|
6
|
+
import { declinesOf, fetchContext, reportReview } from "./cloud.js";
|
|
7
|
+
import { GitHub } from "./publish/api.js";
|
|
8
|
+
import { writeAccess } from "./publish/handled.js";
|
|
9
|
+
import { publishTeamChecks } from "./publish/team-checks.js";
|
|
10
|
+
import { approveCheck, checkLimitTitle, checkLoginTitle, failCheck, failSummary, previousFindings, publishReview, startCheck, startSummary, syncApproval, UNREVIEWED } from "./publish/publish.js";
|
|
11
|
+
import { LimitError, LoginError, loginFailureMessage } from "./providers/codex.js";
|
|
12
|
+
import { limitNotice, loginNotice } from "./publish/markdown.js";
|
|
13
|
+
import { renderRejected, renderTerminal } from "./render.js";
|
|
14
|
+
import { reviewPullRequest } from "./review.js";
|
|
15
|
+
import { askForApp, connect, githubConnect } from "./connect.js";
|
|
16
|
+
import { init, realInitDeps } from "./init.js";
|
|
17
|
+
import { realDeps, setup } from "./setup.js";
|
|
18
|
+
const HELP = `Mergelight: AI code review on the plan you already pay for.
|
|
19
|
+
|
|
20
|
+
Usage
|
|
21
|
+
mergelight review <pr> [options] Review a pull request
|
|
22
|
+
mergelight post <review.json> Post a saved review to its pull request
|
|
23
|
+
mergelight approve <pr> --by <login> Turn a "needs a human" check green after approval
|
|
24
|
+
mergelight init Add Mergelight to your coding agents: Claude Code, Codex and Cursor
|
|
25
|
+
mergelight mcp Run the MCP server, so your coding agent can read findings
|
|
26
|
+
mergelight setup <owner/repo> Set up the GitHub Action on a repository
|
|
27
|
+
mergelight connect <pr> In the Action: connect ChatGPT from the pull request
|
|
28
|
+
|
|
29
|
+
<pr> is a pull request URL, owner/repo#123, or a number inside a clone.
|
|
30
|
+
|
|
31
|
+
Options
|
|
32
|
+
--repo <owner/name> Repository for a bare PR number
|
|
33
|
+
--at <sha> Review this commit of the PR instead of the latest
|
|
34
|
+
--post Post the review to the PR: summary comment, inline findings, check
|
|
35
|
+
(the check needs a GitHub App, a personal gh login skips it)
|
|
36
|
+
--dry-run With --post, post or approve: print what would be posted, change nothing
|
|
37
|
+
--yellow-blocks With --post or post: a "needs a human" check waits for an approval
|
|
38
|
+
--json Print the review as JSON
|
|
39
|
+
--out <file> Also write the JSON review to a file
|
|
40
|
+
--provider <name> Who hunts for problems: codex or claude (default: codex)
|
|
41
|
+
--model <name> Model for the hunters (default: your Codex config, or opus on Claude)
|
|
42
|
+
--effort <level> Reasoning effort: low, medium, high (default: high)
|
|
43
|
+
--verify-with <name> Who checks the findings: claude or codex
|
|
44
|
+
(default: claude when Claude Code is installed)
|
|
45
|
+
--verify-model <name> Model for the checker (default for claude: opus)
|
|
46
|
+
--keep Keep the temporary checkout
|
|
47
|
+
--by <login> Who approved, for approve
|
|
48
|
+
With approve, --at is the commit they approved: an older one doesn't count
|
|
49
|
+
--base <branch> For setup: add the workflows to this branch (default: the default branch)
|
|
50
|
+
--skip-branches <a,b> For setup: don't review pull requests from these branches
|
|
51
|
+
--relogin For setup: log in to Codex again
|
|
52
|
+
--no-pin For setup: follow @v0 and get each release by itself, instead of pinning to the latest
|
|
53
|
+
--yes For setup: don't stop to ask whether the app is installed
|
|
54
|
+
--no-save For connect: there's nowhere to save a login, so ask for the app instead
|
|
55
|
+
-h, --help Show this help
|
|
56
|
+
|
|
57
|
+
Reviews run on your own logged-in Codex CLI, and Claude Code if you check with it.
|
|
58
|
+
Nothing is sent to Mergelight.
|
|
59
|
+
`;
|
|
60
|
+
function progressPrinter() {
|
|
61
|
+
const tty = Boolean(process.stderr.isTTY);
|
|
62
|
+
const started = Date.now();
|
|
63
|
+
let last = "";
|
|
64
|
+
const draw = () => {
|
|
65
|
+
if (!tty || !last)
|
|
66
|
+
return;
|
|
67
|
+
const s = Math.round((Date.now() - started) / 1000);
|
|
68
|
+
const line = `${last} (${s}s)`;
|
|
69
|
+
process.stderr.write(`\r\x1b[2K${line.slice(0, (process.stderr.columns ?? 100) - 1)}`);
|
|
70
|
+
};
|
|
71
|
+
const ticker = tty ? setInterval(draw, 1000) : undefined;
|
|
72
|
+
return {
|
|
73
|
+
onProgress(message, transient) {
|
|
74
|
+
if (tty) {
|
|
75
|
+
last = message;
|
|
76
|
+
draw();
|
|
77
|
+
}
|
|
78
|
+
else if (!transient) {
|
|
79
|
+
process.stderr.write(`${message}\n`);
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
stop() {
|
|
83
|
+
if (ticker)
|
|
84
|
+
clearInterval(ticker);
|
|
85
|
+
if (tty)
|
|
86
|
+
process.stderr.write("\r\x1b[2K");
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
const log = (line) => process.stderr.write(`${line}\n`);
|
|
91
|
+
async function main() {
|
|
92
|
+
const { values, positionals } = parseArgs({
|
|
93
|
+
allowPositionals: true,
|
|
94
|
+
options: {
|
|
95
|
+
repo: { type: "string" },
|
|
96
|
+
at: { type: "string" },
|
|
97
|
+
post: { type: "boolean" },
|
|
98
|
+
"dry-run": { type: "boolean" },
|
|
99
|
+
"yellow-blocks": { type: "boolean" },
|
|
100
|
+
json: { type: "boolean" },
|
|
101
|
+
out: { type: "string" },
|
|
102
|
+
model: { type: "string" },
|
|
103
|
+
effort: { type: "string" },
|
|
104
|
+
"verify-with": { type: "string" },
|
|
105
|
+
provider: { type: "string" },
|
|
106
|
+
"verify-model": { type: "string" },
|
|
107
|
+
keep: { type: "boolean" },
|
|
108
|
+
by: { type: "string" },
|
|
109
|
+
base: { type: "string" },
|
|
110
|
+
"skip-branches": { type: "string" },
|
|
111
|
+
relogin: { type: "boolean" },
|
|
112
|
+
pin: { type: "boolean" },
|
|
113
|
+
"no-pin": { type: "boolean" },
|
|
114
|
+
yes: { type: "boolean" },
|
|
115
|
+
"no-save": { type: "boolean" },
|
|
116
|
+
help: { type: "boolean", short: "h" },
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
const [command, target] = positionals;
|
|
120
|
+
if (values.help || !command) {
|
|
121
|
+
process.stdout.write(HELP);
|
|
122
|
+
return values.help ? 0 : 1;
|
|
123
|
+
}
|
|
124
|
+
if (command === "setup") {
|
|
125
|
+
if (!target || !/^[\w.-]+\/[\w.-]+$/.test(target)) {
|
|
126
|
+
log("mergelight: name the repository, like: mergelight setup owner/repo");
|
|
127
|
+
return 1;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
return await setup({
|
|
131
|
+
repo: target,
|
|
132
|
+
base: values.base,
|
|
133
|
+
skipBranches: values["skip-branches"]?.split(",").map((b) => b.trim()).filter(Boolean),
|
|
134
|
+
relogin: values.relogin,
|
|
135
|
+
pin: !values["no-pin"],
|
|
136
|
+
yes: values.yes,
|
|
137
|
+
}, realDeps());
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
log(`mergelight: ${err instanceof Error ? err.message : String(err)}`);
|
|
141
|
+
return 1;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (command === "init") {
|
|
145
|
+
try {
|
|
146
|
+
return await init(realInitDeps());
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
log(`mergelight: ${err instanceof Error ? err.message : String(err)}`);
|
|
150
|
+
return 1;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (command === "mcp") {
|
|
154
|
+
await serve();
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
if (!["review", "post", "approve", "connect"].includes(command) || !target) {
|
|
158
|
+
process.stderr.write(HELP);
|
|
159
|
+
return 1;
|
|
160
|
+
}
|
|
161
|
+
const dryRun = Boolean(values["dry-run"]);
|
|
162
|
+
const provider = values.provider;
|
|
163
|
+
if (provider !== undefined && provider !== "codex" && provider !== "claude") {
|
|
164
|
+
log(`mergelight: --provider must be codex or claude, not "${provider}"`);
|
|
165
|
+
return 1;
|
|
166
|
+
}
|
|
167
|
+
const verifyWith = values["verify-with"];
|
|
168
|
+
if (verifyWith !== undefined && verifyWith !== "codex" && verifyWith !== "claude") {
|
|
169
|
+
log(`mergelight: --verify-with must be codex or claude, not "${verifyWith}"`);
|
|
170
|
+
return 1;
|
|
171
|
+
}
|
|
172
|
+
if (command === "post") {
|
|
173
|
+
const review = JSON.parse(readFileSync(target, "utf8"));
|
|
174
|
+
const result = await publishReview(review, { dryRun, log, yellowBlocks: values["yellow-blocks"] });
|
|
175
|
+
log(`Posted: ${result.inline} inline, ${result.outside} in the summary only, ${result.resolved} resolved. ${result.summaryUrl ?? ""}`);
|
|
176
|
+
return 0;
|
|
177
|
+
}
|
|
178
|
+
const ref = parsePrRef(target, values.repo ?? (await currentRepo()));
|
|
179
|
+
if (command === "connect") {
|
|
180
|
+
try {
|
|
181
|
+
const api = new GitHub(ref.owner, ref.repo, { log });
|
|
182
|
+
const { headSha } = await fetchPullRequest(ref);
|
|
183
|
+
if (values["no-save"]) {
|
|
184
|
+
await askForApp(api, ref.number, headSha);
|
|
185
|
+
log("Install the Mergelight AI app: without it there's nowhere to save the ChatGPT login.");
|
|
186
|
+
return 1;
|
|
187
|
+
}
|
|
188
|
+
return await connect(githubConnect(api, ref.number, headSha, log));
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
log(`mergelight: ${err instanceof Error ? err.message : String(err)}`);
|
|
192
|
+
return 1;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (command === "approve") {
|
|
196
|
+
if (!values.by) {
|
|
197
|
+
log("approve needs --by <login>");
|
|
198
|
+
return 1;
|
|
199
|
+
}
|
|
200
|
+
log(await approveCheck(new GitHub(ref.owner, ref.repo, { dryRun, log }), ref.number, values.by, values.at || undefined));
|
|
201
|
+
return 0;
|
|
202
|
+
}
|
|
203
|
+
// review
|
|
204
|
+
const api = new GitHub(ref.owner, ref.repo, { dryRun, log });
|
|
205
|
+
let checkRunId = null;
|
|
206
|
+
let headSha = values.at ?? null;
|
|
207
|
+
if (values.post) {
|
|
208
|
+
headSha ??= (await fetchPullRequest(ref)).headSha;
|
|
209
|
+
checkRunId = await startCheck(api, headSha);
|
|
210
|
+
await startSummary(api, ref.number).catch((e) => log(`Couldn't post the summary yet: ${e.message}`));
|
|
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: [] };
|
|
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;
|
|
218
|
+
try {
|
|
219
|
+
// The login step already found this login can't be refreshed, so don't send every reviewer to find out.
|
|
220
|
+
if (process.env.MERGELIGHT_LOGIN_LOST === "1")
|
|
221
|
+
throw new LoginError(loginFailureMessage(process.env.SECRET_NAME || undefined));
|
|
222
|
+
const previous = values.post ? await previousFindings(api, ref.number) : undefined;
|
|
223
|
+
const review = await reviewPullRequest(ref, {
|
|
224
|
+
previous,
|
|
225
|
+
memories: cloud.memories,
|
|
226
|
+
rules: cloud.rules,
|
|
227
|
+
rulesUnread: cloud.failed === true,
|
|
228
|
+
skills: cloud.skills,
|
|
229
|
+
checks: cloud.checks,
|
|
230
|
+
onTeamChecks: (results) => (answered = results),
|
|
231
|
+
at: values.at,
|
|
232
|
+
provider,
|
|
233
|
+
model: values.model,
|
|
234
|
+
effort: values.effort,
|
|
235
|
+
verifyWith,
|
|
236
|
+
verifyModel: values["verify-model"],
|
|
237
|
+
keep: values.keep,
|
|
238
|
+
onProgress: progress.onProgress,
|
|
239
|
+
});
|
|
240
|
+
progress.stop();
|
|
241
|
+
const json = JSON.stringify(review, null, 2);
|
|
242
|
+
if (values.out)
|
|
243
|
+
writeFileSync(values.out, `${json}\n`);
|
|
244
|
+
process.stdout.write(values.json ? `${json}\n` : `${renderTerminal(review)}\n`);
|
|
245
|
+
// GitHub sets RUNNER_DEBUG when someone re-runs a job with debug logging on.
|
|
246
|
+
if (process.env.RUNNER_DEBUG === "1" || process.env.MERGELIGHT_DEBUG === "1")
|
|
247
|
+
for (const line of renderRejected(review))
|
|
248
|
+
log(line);
|
|
249
|
+
if (values.post) {
|
|
250
|
+
const result = await publishReview(review, { dryRun, log, checkRunId, yellowBlocks: values["yellow-blocks"], teamUnread: cloud.failed === true });
|
|
251
|
+
log(`Posted: ${result.inline} inline, ${result.outside} in the summary only, ${result.resolved} resolved. ${result.summaryUrl ?? ""}`);
|
|
252
|
+
if (review.team_checks?.length) {
|
|
253
|
+
checksPosted = true;
|
|
254
|
+
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));
|
|
255
|
+
if (posted)
|
|
256
|
+
log(`Posted ${posted} of your team's check${posted === 1 ? "" : "s"}.`);
|
|
257
|
+
}
|
|
258
|
+
if (cloud.connected) {
|
|
259
|
+
// A decision is only remembered when GitHub says its author can push to this repository. Being a
|
|
260
|
+
// member of the org is not enough: this outlives the pull request it was made on.
|
|
261
|
+
const canWrite = writeAccess(api);
|
|
262
|
+
const declines = [];
|
|
263
|
+
for (const d of declinesOf(previous))
|
|
264
|
+
if (await canWrite(d.by))
|
|
265
|
+
declines.push(d);
|
|
266
|
+
await reportReview(review, { log }, declines);
|
|
267
|
+
}
|
|
268
|
+
// The check carries the verdict; the job itself only fails on errors.
|
|
269
|
+
return 0;
|
|
270
|
+
}
|
|
271
|
+
return review.light === "red" ? 2 : 0;
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
progress.stop();
|
|
275
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
276
|
+
log(`mergelight: ${message}`);
|
|
277
|
+
if (values.post && headSha) {
|
|
278
|
+
const login = err instanceof LoginError ? err : null;
|
|
279
|
+
const limit = err instanceof LimitError ? err : null;
|
|
280
|
+
const title = limit ? checkLimitTitle(limit.plan) : login ? checkLoginTitle(login.plan) : undefined;
|
|
281
|
+
const notice = limit ? limitNotice(limit.plan, limit.resets) : login ? loginNotice(login.plan, message) : undefined;
|
|
282
|
+
await failCheck(api, checkRunId, headSha, message, log, title).catch((e) => log(`Couldn't update the check: ${e.message}`));
|
|
283
|
+
await failSummary(api, ref.number, notice).catch((e) => log(`Couldn't update the summary: ${e.message}`));
|
|
284
|
+
// The newest commit wasn't reviewed. An approval Mergelight gave to an earlier commit must not count for this one.
|
|
285
|
+
await syncApproval(api, ref.number, "yellow", headSha, log, { why: UNREVIEWED, otherCommitsOnly: true });
|
|
286
|
+
// Each of the team's checks still gets an answer on GitHub, so a required one says why it holds the merge:
|
|
287
|
+
// the answer it already has, or that it wasn't asked.
|
|
288
|
+
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: [] }));
|
|
289
|
+
const owed = checksPosted ? [] : (answered ?? unasked);
|
|
290
|
+
if (owed.length)
|
|
291
|
+
await publishTeamChecks(api, headSha, owed, log).catch((e) => log(`Couldn't post your team's checks: ${e.message}`));
|
|
292
|
+
}
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
main().then((code) => process.exit(code));
|
package/dist/cloud.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { isSkillPath } 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: [] };
|
|
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, 500))
|
|
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
|
+
if (typeof c.name !== "string" || c.name.length > 40 || !/^[A-Za-z0-9](?:[A-Za-z0-9._-]| (?! ))*$/.test(c.name) || c.name.endsWith(" "))
|
|
216
|
+
continue;
|
|
217
|
+
if (!Array.isArray(c.paths) || c.paths.length < 1 || c.paths.length > 10 || !c.paths.every(isPattern))
|
|
218
|
+
continue;
|
|
219
|
+
if (checks.some((other) => other.name.toLowerCase() === c.name.toLowerCase()))
|
|
220
|
+
continue;
|
|
221
|
+
checks.push({ id: c.id, name: c.name, text: c.text, paths: c.paths });
|
|
222
|
+
}
|
|
223
|
+
return checks;
|
|
224
|
+
}
|
|
225
|
+
export function readRules(value) {
|
|
226
|
+
if (!Array.isArray(value))
|
|
227
|
+
return [];
|
|
228
|
+
const rules = [];
|
|
229
|
+
for (const raw of value.slice(0, 100)) {
|
|
230
|
+
const r = raw;
|
|
231
|
+
if (!r || typeof r !== "object")
|
|
232
|
+
continue;
|
|
233
|
+
if (typeof r.id !== "string" || !/^R\d{1,12}$/.test(r.id) || !isText(r.text, 300))
|
|
234
|
+
continue;
|
|
235
|
+
if ((r.kind !== "rule" && r.kind !== "needs_human") || (r.scope !== "org" && r.scope !== "repo"))
|
|
236
|
+
continue;
|
|
237
|
+
const paths = r.paths === undefined || r.paths === null ? [] : r.paths;
|
|
238
|
+
if (!Array.isArray(paths) || paths.length > 10 || !paths.every(isPattern))
|
|
239
|
+
continue;
|
|
240
|
+
// "Always needs a human" is about files, so one that names none says nothing.
|
|
241
|
+
if (r.kind === "needs_human" && !paths.length)
|
|
242
|
+
continue;
|
|
243
|
+
rules.push({ id: r.id, kind: r.kind, text: r.text, ...(paths.length ? { paths: paths } : {}), scope: r.scope });
|
|
244
|
+
}
|
|
245
|
+
return rules;
|
|
246
|
+
}
|
|
247
|
+
/** Asks the server what this review should know. Never throws: without an answer the review runs as it always has. */
|
|
248
|
+
export async function fetchContext(deps = {}) {
|
|
249
|
+
const d = defaults(deps);
|
|
250
|
+
const server = serverOrSay(d);
|
|
251
|
+
if (!server)
|
|
252
|
+
return NOTHING;
|
|
253
|
+
try {
|
|
254
|
+
const res = await call(d, server, "/v1/context", { method: "GET" });
|
|
255
|
+
if (!res.ok) {
|
|
256
|
+
d.log(`The Mergelight server answered ${res.status}. The review runs without it.`);
|
|
257
|
+
return { ...NOTHING, failed: true };
|
|
258
|
+
}
|
|
259
|
+
const answer = res.answer;
|
|
260
|
+
if (answer?.connected !== true)
|
|
261
|
+
return NOTHING;
|
|
262
|
+
const skills = Array.isArray(answer.skills) ? answer.skills.filter(isSkillPath).slice(0, 10) : [];
|
|
263
|
+
return { connected: true, memories: readMemories(answer.memories), rules: readRules(answer.rules), skills, checks: readChecks(answer.checks) };
|
|
264
|
+
}
|
|
265
|
+
catch (err) {
|
|
266
|
+
d.log(`Couldn't reach the Mergelight server (${err.message}). The review runs without it.`);
|
|
267
|
+
return { ...NOTHING, failed: true };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/** True when this repository's org uses the dashboard. */
|
|
271
|
+
export async function cloudConnected(deps = {}) {
|
|
272
|
+
return (await fetchContext(deps)).connected;
|
|
273
|
+
}
|
|
274
|
+
/** The server reads 64 KB per report. The decisions get most of it, and the numbers always fit beside them. */
|
|
275
|
+
const MAX_DECLINE_BYTES = 48_000;
|
|
276
|
+
/**
|
|
277
|
+
* The decisions on this pull request that are worth remembering: someone wrote a mark that says
|
|
278
|
+
* "not fixing this" and gave a reason. A resolved thread has no reason, so it isn't one.
|
|
279
|
+
*/
|
|
280
|
+
export function declinesOf(previous) {
|
|
281
|
+
// Line breaks and control characters become spaces: a reason is one line of plain text by the time it is sent.
|
|
282
|
+
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();
|
|
283
|
+
const declines = [];
|
|
284
|
+
for (const p of previous ?? []) {
|
|
285
|
+
const h = p.handled;
|
|
286
|
+
if (!h || h.as !== "wont_fix" || h.from !== "mark" || !h.note?.trim())
|
|
287
|
+
continue;
|
|
288
|
+
if (!/^[a-f0-9]{6,40}$/.test(p.id) || !/^[\w.-]{1,100}(\[bot\])?$/.test(h.by) || !isLine(p.line))
|
|
289
|
+
continue;
|
|
290
|
+
const title = clean(p.title, 200);
|
|
291
|
+
const file = clean(p.file, 400);
|
|
292
|
+
const reason = clean(h.note, 500);
|
|
293
|
+
const at = Date.parse(h.at ?? "");
|
|
294
|
+
if (!title || !file || !reason || !Number.isFinite(at))
|
|
295
|
+
continue;
|
|
296
|
+
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() });
|
|
297
|
+
}
|
|
298
|
+
// What fits one report, counted in bytes: a reason in another alphabet takes more of them than letters.
|
|
299
|
+
const fit = [];
|
|
300
|
+
let bytes = 0;
|
|
301
|
+
for (const d of declines.slice(0, 40)) {
|
|
302
|
+
bytes += Buffer.byteLength(JSON.stringify(d)) + 1;
|
|
303
|
+
if (bytes > MAX_DECLINE_BYTES)
|
|
304
|
+
break;
|
|
305
|
+
fit.push(d);
|
|
306
|
+
}
|
|
307
|
+
return fit;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Sends the review's numbers for the dashboard, with the team's new decisions to remember and the
|
|
311
|
+
* earlier ones this review used. Returns whether the server took them.
|
|
312
|
+
*/
|
|
313
|
+
export async function reportReview(review, deps = {}, declines = []) {
|
|
314
|
+
const d = defaults(deps);
|
|
315
|
+
const server = serverUrl(d.env);
|
|
316
|
+
if (!server)
|
|
317
|
+
return false;
|
|
318
|
+
try {
|
|
319
|
+
// One id for this report, the same on both tries, so the server keeps it once.
|
|
320
|
+
const used = (review.used_memories ?? []).filter((id) => /^M\d{1,12}$/.test(id)).slice(0, 200);
|
|
321
|
+
const body = JSON.stringify({ ...reviewNumbers(review), report_id: randomUUID(), ...(declines.length ? { declines } : {}), ...(used.length ? { used_memories: used } : {}) });
|
|
322
|
+
const res = await call(d, server, "/v1/reviews", { method: "POST", body });
|
|
323
|
+
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.`);
|
|
324
|
+
return res.ok;
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
d.log(`Couldn't send the review's numbers to the Mergelight server (${err.message}). The review itself is posted.`);
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
}
|