@mergelight/cli 0.1.14 → 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/dist/checks.js +108 -0
- package/dist/cli.js +49 -5
- package/dist/cloud.js +330 -0
- package/dist/mcp/findings.js +5 -0
- package/dist/prompt.js +251 -5
- package/dist/providers/codex.js +26 -0
- package/dist/publish/handled.js +22 -4
- package/dist/publish/markdown.js +3 -1
- package/dist/publish/publish.js +40 -10
- package/dist/publish/team-checks.js +72 -0
- package/dist/render.js +23 -0
- package/dist/review.js +101 -6
- package/dist/schema.js +49 -0
- package/dist/skills.js +127 -0
- package/dist/workspace.js +184 -3
- package/package.json +1 -1
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, 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 { 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";
|
|
@@ -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,13 +209,25 @@ 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: [] };
|
|
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
|
+
const previous = values.post ? await previousFindings(api, ref.number) : undefined;
|
|
213
223
|
const review = await reviewPullRequest(ref, {
|
|
214
|
-
previous
|
|
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),
|
|
215
231
|
at: values.at,
|
|
216
232
|
provider,
|
|
217
233
|
model: values.model,
|
|
@@ -226,9 +242,29 @@ async function main() {
|
|
|
226
242
|
if (values.out)
|
|
227
243
|
writeFileSync(values.out, `${json}\n`);
|
|
228
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);
|
|
229
249
|
if (values.post) {
|
|
230
|
-
const result = await publishReview(review, { dryRun, log, checkRunId, yellowBlocks: values["yellow-blocks"] });
|
|
250
|
+
const result = await publishReview(review, { dryRun, log, checkRunId, yellowBlocks: values["yellow-blocks"], teamUnread: cloud.failed === true });
|
|
231
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
|
+
}
|
|
232
268
|
// The check carries the verdict; the job itself only fails on errors.
|
|
233
269
|
return 0;
|
|
234
270
|
}
|
|
@@ -245,6 +281,14 @@ async function main() {
|
|
|
245
281
|
const notice = limit ? limitNotice(limit.plan, limit.resets) : login ? loginNotice(login.plan, message) : undefined;
|
|
246
282
|
await failCheck(api, checkRunId, headSha, message, log, title).catch((e) => log(`Couldn't update the check: ${e.message}`));
|
|
247
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}`));
|
|
248
292
|
}
|
|
249
293
|
return 1;
|
|
250
294
|
}
|
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
|
+
}
|
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.`);
|