@mergelight/cli 0.0.0-stage → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +110 -0
- package/README.md +113 -2
- package/dist/action-source.js +107 -0
- package/dist/checks.js +108 -0
- package/dist/cli.js +296 -0
- package/dist/cloud.js +330 -0
- package/dist/connect-claude.js +157 -0
- package/dist/connect.js +319 -0
- package/dist/github.js +65 -0
- package/dist/init.js +92 -0
- package/dist/mcp/findings.js +252 -0
- package/dist/mcp/server.js +168 -0
- package/dist/prompt.js +503 -0
- package/dist/providers/claude.js +102 -0
- package/dist/providers/codex.js +251 -0
- package/dist/providers/index.js +8 -0
- package/dist/publish/api.js +63 -0
- package/dist/publish/closed.js +88 -0
- package/dist/publish/diff-lines.js +50 -0
- package/dist/publish/handled.js +98 -0
- package/dist/publish/markdown.js +233 -0
- package/dist/publish/publish.js +397 -0
- package/dist/publish/state.js +82 -0
- package/dist/publish/team-checks.js +72 -0
- package/dist/render.js +129 -0
- package/dist/review.js +366 -0
- package/dist/run.js +57 -0
- package/dist/schema.js +155 -0
- package/dist/setup.js +180 -0
- package/dist/skills.js +127 -0
- package/dist/types.js +1 -0
- package/dist/update.js +36 -0
- package/dist/workspace.js +318 -0
- package/package.json +36 -4
- package/scripts/app-token.mjs +69 -0
- package/scripts/mask-login.mjs +26 -0
- package/scripts/refresh-login.mjs +171 -0
- package/scripts/save-claude-login.sh +22 -0
- package/scripts/save-login.sh +30 -0
- package/skills/mergelight/SKILL.md +66 -0
- package/templates/mergelight-approve.yml +21 -0
- package/templates/mergelight-refresh.yml +23 -0
- package/templates/mergelight.yml +42 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { run } from "../run.js";
|
|
5
|
+
/** Codex's Linux sandbox (bubblewrap) can't start, so every command fails. */
|
|
6
|
+
export class SandboxError extends Error {
|
|
7
|
+
}
|
|
8
|
+
/** The ChatGPT login didn't work. Worth saying plainly, because re-running usually fixes it. */
|
|
9
|
+
export class LoginError extends Error {
|
|
10
|
+
plan;
|
|
11
|
+
constructor(message, plan = "ChatGPT") {
|
|
12
|
+
super(message);
|
|
13
|
+
this.plan = plan;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** The plan has no usage left. Nothing is broken, so the person only needs to know that and when it comes back. */
|
|
17
|
+
export class LimitError extends Error {
|
|
18
|
+
plan;
|
|
19
|
+
resets;
|
|
20
|
+
constructor(plan, resets) {
|
|
21
|
+
super(`Your ${plan} plan hit its usage limit.${resets ? ` Resets: ${resets}.` : ""}`);
|
|
22
|
+
this.plan = plan;
|
|
23
|
+
this.resets = resets;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Both programs start this sentence the same way. Only pass in their own errors: code under review can say anything. */
|
|
27
|
+
const LIMIT_HIT = /you['\u2019]ve hit your\b[^\n]{0,40}\blimit\b/i;
|
|
28
|
+
const WHEN = "[\\w :,()+-]{1,60}";
|
|
29
|
+
/** The limit in a program's error output, if that's what the error is. Claude says "resets 9am (UTC)", Codex "try again at 3:14 PM". */
|
|
30
|
+
export function limitFrom(text, plan) {
|
|
31
|
+
const line = text.split("\n").find((l) => LIMIT_HIT.test(l));
|
|
32
|
+
if (!line)
|
|
33
|
+
return null;
|
|
34
|
+
const resets = line.match(new RegExp(`\\bresets\\s+(${WHEN})`, "i"))?.[1]?.trim();
|
|
35
|
+
if (resets)
|
|
36
|
+
return new LimitError(plan, resets);
|
|
37
|
+
const retry = line.match(new RegExp(`\\btry again at\\s+(${WHEN})`, "i"))?.[1]?.trim();
|
|
38
|
+
// Codex prints the runner's clock with no zone, and a time with no zone reads as the person's own.
|
|
39
|
+
const zone = retry && new Date().getTimezoneOffset() === 0 && !/UTC|GMT/.test(retry) ? " UTC" : "";
|
|
40
|
+
return new LimitError(plan, retry ? `${retry}${zone}` : null);
|
|
41
|
+
}
|
|
42
|
+
/** What Codex says when a login is refused or can't be refreshed. */
|
|
43
|
+
const LOGIN_FAILURE = /access token could not be refreshed|401 Unauthorized/i;
|
|
44
|
+
export function loginFailureMessage(secretName = "CODEX_AUTH_JSON") {
|
|
45
|
+
return `The ChatGPT login didn't work, most likely because another run already refreshed it. Re-run the Mergelight job from the Actions tab, or push again, to pick up the new one. If it fails again, the login has stopped working: delete the ${secretName} secret, then push, and this pull request shows a code to connect ChatGPT again.`;
|
|
46
|
+
}
|
|
47
|
+
const SANDBOX_FAILURE = /bwrap:|user namespace|new namespace|RTM_NEWADDR|uid map|sandbox.*(denied|not permitted)/i;
|
|
48
|
+
function codexHome() {
|
|
49
|
+
return process.env.CODEX_HOME ?? join(homedir(), ".codex");
|
|
50
|
+
}
|
|
51
|
+
function readUserConfig() {
|
|
52
|
+
try {
|
|
53
|
+
return readFileSync(join(codexHome(), "config.toml"), "utf8");
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return "";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** The model from the user's Codex config, for display only. */
|
|
60
|
+
export function configuredModel(config = readUserConfig()) {
|
|
61
|
+
const top = config.split(/^\[/m)[0] ?? "";
|
|
62
|
+
return top.match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1] ?? null;
|
|
63
|
+
}
|
|
64
|
+
/** Names of MCP servers in the user's Codex config, so they can be switched off for reviews. */
|
|
65
|
+
function mcpServers(config) {
|
|
66
|
+
const names = new Set();
|
|
67
|
+
for (const m of config.matchAll(/^\[mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))\]\s*$/gm)) {
|
|
68
|
+
const name = m[1] ?? m[2];
|
|
69
|
+
if (name && !name.includes("."))
|
|
70
|
+
names.add(name);
|
|
71
|
+
}
|
|
72
|
+
return [...names];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Commands Codex runs can read the whole disk but not write or reach the network. Code under review can try to
|
|
76
|
+
* steer them, so the folder with the login is taken out of what they can read. Codex itself still reads it.
|
|
77
|
+
*/
|
|
78
|
+
export function sandboxArgs(home = codexHome()) {
|
|
79
|
+
return ["-c", 'default_permissions="mergelight_review"', "-c", `permissions.mergelight_review.filesystem={":root"="read",${JSON.stringify(home)}="none"}`];
|
|
80
|
+
}
|
|
81
|
+
/** Tokens the runner holds that a reviewing agent has no use for. It only needs its own login. */
|
|
82
|
+
const HIDDEN_ENV = new Set(["GH_TOKEN", "GITHUB_TOKEN", "SECRETS_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_RUNTIME_TOKEN", "ACTIONS_RESULTS_URL", "ACTIONS_CACHE_URL", "MERGELIGHT_CLAUDE_TOKEN"]);
|
|
83
|
+
export function agentEnv(env = process.env) {
|
|
84
|
+
return Object.fromEntries(Object.entries(env).filter(([name]) => !HIDDEN_ENV.has(name)));
|
|
85
|
+
}
|
|
86
|
+
/** Codex also has no use for a Claude login. */
|
|
87
|
+
export function codexEnv(env = process.env) {
|
|
88
|
+
const { CLAUDE_CODE_OAUTH_TOKEN: _token, ANTHROPIC_API_KEY: _key, ...rest } = agentEnv(env);
|
|
89
|
+
return rest;
|
|
90
|
+
}
|
|
91
|
+
const JWT = /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]+/g;
|
|
92
|
+
const ANTHROPIC_SECRET = /\bsk-ant-[\w-]{20,}/g;
|
|
93
|
+
/** Takes login tokens out of text that's about to be posted, in case one got past the sandbox. */
|
|
94
|
+
export function scrubSecrets(text, home = codexHome(), env = process.env) {
|
|
95
|
+
let secrets = [];
|
|
96
|
+
try {
|
|
97
|
+
const { tokens, OPENAI_API_KEY: key } = JSON.parse(readFileSync(join(home, "auth.json"), "utf8"));
|
|
98
|
+
secrets = [...Object.values(tokens ?? {}), key].filter((v) => typeof v === "string" && v.length >= 20);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// No login file to compare with. The pattern below still applies.
|
|
102
|
+
}
|
|
103
|
+
secrets.push(...[env.CLAUDE_CODE_OAUTH_TOKEN, env.ANTHROPIC_API_KEY].filter((v) => typeof v === "string" && v.length >= 20));
|
|
104
|
+
return secrets.reduce((out, secret) => out.split(secret).join("[removed]"), text).replace(JWT, "[removed]").replace(ANTHROPIC_SECRET, "[removed]");
|
|
105
|
+
}
|
|
106
|
+
let features;
|
|
107
|
+
/** The feature switches this Codex has. Codex stops at one it doesn't know, so a switch is only used where it exists. */
|
|
108
|
+
function codexFeatures() {
|
|
109
|
+
features ??= run("codex", ["features", "list"], { timeoutMs: 15_000 })
|
|
110
|
+
.then((r) => {
|
|
111
|
+
if (r.code !== 0)
|
|
112
|
+
throw new Error("codex features list failed");
|
|
113
|
+
return new Set(r.stdout.split("\n").map((line) => line.trim().split(/\s+/)[0] ?? "").filter(Boolean));
|
|
114
|
+
})
|
|
115
|
+
.catch(() => {
|
|
116
|
+
// Not kept: the next run asks again.
|
|
117
|
+
features = undefined;
|
|
118
|
+
return new Set();
|
|
119
|
+
});
|
|
120
|
+
return features;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Switches for a run that must not take instructions from files in its working directory. Codex
|
|
124
|
+
* reads AGENTS.md there by itself and follows it, and it tells the model about every skill it finds
|
|
125
|
+
* under .codex/skills and .agents/skills, which the model then follows too. Tested with Codex
|
|
126
|
+
* 0.167: a planted file of either kind was obeyed, and with these switches it wasn't.
|
|
127
|
+
*/
|
|
128
|
+
export async function withoutProjectDocs(has = codexFeatures()) {
|
|
129
|
+
return ["-c", "project_doc_max_bytes=0", ...((await has).has("omit_skill_descriptions") ? ["--enable", "omit_skill_descriptions"] : [])];
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Runs the user's own logged-in Codex CLI, headless, in a sandbox that can read but not write or reach the network.
|
|
133
|
+
* Plugins, MCP servers, hooks and notifications are switched off for the run,
|
|
134
|
+
* so code in a pull request can't steer the reviewer into the user's other tools.
|
|
135
|
+
* Everything else (provider, model, login) is the user's own Codex setup.
|
|
136
|
+
*/
|
|
137
|
+
export async function runCodex(opts) {
|
|
138
|
+
const config = readUserConfig();
|
|
139
|
+
const work = mkdtempSync(join(tmpdir(), "mergelight-codex-"));
|
|
140
|
+
const schemaFile = join(work, "schema.json");
|
|
141
|
+
const outFile = join(work, "output.json");
|
|
142
|
+
writeFileSync(schemaFile, JSON.stringify(opts.schema));
|
|
143
|
+
const args = [
|
|
144
|
+
"exec",
|
|
145
|
+
...sandboxArgs(),
|
|
146
|
+
"--ephemeral",
|
|
147
|
+
"--skip-git-repo-check",
|
|
148
|
+
"--json",
|
|
149
|
+
"-C", opts.cwd,
|
|
150
|
+
"--output-schema", schemaFile,
|
|
151
|
+
"-o", outFile,
|
|
152
|
+
...["plugins", "apps", "hooks", "image_generation", "browser_use", "computer_use"].flatMap((f) => ["--disable", f]),
|
|
153
|
+
"-c", "notify=[]",
|
|
154
|
+
...(opts.projectDocs === true ? [] : await withoutProjectDocs()),
|
|
155
|
+
"-c", 'web_search="disabled"',
|
|
156
|
+
...mcpServers(config).flatMap((name) => ["-c", `mcp_servers.${name}.enabled=false`]),
|
|
157
|
+
];
|
|
158
|
+
if (opts.model)
|
|
159
|
+
args.push("-m", opts.model);
|
|
160
|
+
if (opts.effort)
|
|
161
|
+
args.push("-c", `model_reasoning_effort="${opts.effort}"`);
|
|
162
|
+
args.push("-");
|
|
163
|
+
let commands = 0;
|
|
164
|
+
let completed = 0;
|
|
165
|
+
let sandboxFailures = 0;
|
|
166
|
+
let firstSandboxError = "";
|
|
167
|
+
/** Codex's own errors, kept apart from its stdout, which also carries the code it reads. */
|
|
168
|
+
const failures = [];
|
|
169
|
+
let usage = null;
|
|
170
|
+
let buffer = "";
|
|
171
|
+
const onStdout = (chunk) => {
|
|
172
|
+
buffer += chunk;
|
|
173
|
+
let nl;
|
|
174
|
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
|
175
|
+
const line = buffer.slice(0, nl).trim();
|
|
176
|
+
buffer = buffer.slice(nl + 1);
|
|
177
|
+
if (!line.startsWith("{"))
|
|
178
|
+
continue;
|
|
179
|
+
try {
|
|
180
|
+
const event = JSON.parse(line);
|
|
181
|
+
if (event.type === "error" || event.type === "turn.failed")
|
|
182
|
+
failures.push(event.message ?? event.error?.message ?? "");
|
|
183
|
+
if (event.type === "item.started" && event.item?.type === "command_execution") {
|
|
184
|
+
commands++;
|
|
185
|
+
opts.onCommand?.(event.item.command ?? "");
|
|
186
|
+
}
|
|
187
|
+
if (event.type === "item.completed" && event.item?.type === "command_execution") {
|
|
188
|
+
completed++;
|
|
189
|
+
const output = event.item.aggregated_output ?? "";
|
|
190
|
+
if (event.item.exit_code !== 0 && SANDBOX_FAILURE.test(output)) {
|
|
191
|
+
sandboxFailures++;
|
|
192
|
+
firstSandboxError ||= output.split("\n").find((l) => SANDBOX_FAILURE.test(l))?.trim() ?? "";
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (event.type === "turn.completed" && event.usage) {
|
|
196
|
+
usage = {
|
|
197
|
+
input_tokens: event.usage.input_tokens ?? 0,
|
|
198
|
+
output_tokens: event.usage.output_tokens ?? 0,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
/* not an event line */
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
try {
|
|
208
|
+
const result = await run("codex", args, {
|
|
209
|
+
input: opts.prompt,
|
|
210
|
+
timeoutMs: opts.timeoutMs ?? 25 * 60_000,
|
|
211
|
+
onStdout,
|
|
212
|
+
env: codexEnv(),
|
|
213
|
+
});
|
|
214
|
+
if (opts.logFile) {
|
|
215
|
+
mkdirSync(join(opts.logFile, ".."), { recursive: true });
|
|
216
|
+
writeFileSync(opts.logFile, `${result.stdout}\n--- stderr ---\n${result.stderr}`);
|
|
217
|
+
}
|
|
218
|
+
if (result.code !== 0) {
|
|
219
|
+
const tail = scrubSecrets((result.stderr || result.stdout).trim().split("\n").slice(-6).join("\n"));
|
|
220
|
+
const limit = limitFrom(`${result.stderr}\n${failures.join("\n")}`, "ChatGPT");
|
|
221
|
+
if (limit)
|
|
222
|
+
throw limit;
|
|
223
|
+
// Only a ChatGPT login: a refused API key has a different fix.
|
|
224
|
+
if (process.env.MERGELIGHT_CHATGPT === "1" && LOGIN_FAILURE.test(`${result.stderr}\n${failures.join("\n")}`)) {
|
|
225
|
+
throw new LoginError(loginFailureMessage(process.env.SECRET_NAME || undefined));
|
|
226
|
+
}
|
|
227
|
+
throw new Error(`Codex exited with code ${result.code}.${opts.logFile ? ` Log: ${opts.logFile}` : ""}\n${tail}`);
|
|
228
|
+
}
|
|
229
|
+
// Without a working sandbox Codex can't read the code and reviews the diff blind.
|
|
230
|
+
// Better to fail loudly than to post a review that only looks at the diff.
|
|
231
|
+
if (completed > 0 && sandboxFailures === completed) {
|
|
232
|
+
throw new SandboxError(`Codex couldn't run commands in its sandbox on this machine, so it can't read the code (${scrubSecrets(firstSandboxError) || "every command failed"}). On Linux this usually means unprivileged user namespaces are blocked; see docs/github-action.md.`);
|
|
233
|
+
}
|
|
234
|
+
let raw;
|
|
235
|
+
try {
|
|
236
|
+
raw = readFileSync(outFile, "utf8");
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
throw new Error(`Codex finished without a final answer.${opts.logFile ? ` Log: ${opts.logFile}` : ""}`);
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
output: JSON.parse(scrubSecrets(raw)),
|
|
243
|
+
model: opts.model ?? configuredModel(config),
|
|
244
|
+
commands,
|
|
245
|
+
usage,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
rmSync(work, { recursive: true, force: true });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { runClaude } from "./claude.js";
|
|
2
|
+
export { claudeAvailable } from "./claude.js";
|
|
3
|
+
import { runCodex } from "./codex.js";
|
|
4
|
+
/** How each provider's agent reads the checkout, so prompts can name the right tools. */
|
|
5
|
+
export const TOOLING = { codex: "shell", claude: "files" };
|
|
6
|
+
export function runModel(provider, opts) {
|
|
7
|
+
return provider === "claude" ? runClaude(opts) : runCodex(opts);
|
|
8
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { run } from "../run.js";
|
|
2
|
+
const TRANSIENT = /HTTP 5\d\d|HTTP 429|timed? ?out|ECONNRESET|EAI_AGAIN|connection reset|secondary rate limit/i;
|
|
3
|
+
async function gh(args, input) {
|
|
4
|
+
let lastError = "";
|
|
5
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
6
|
+
if (attempt)
|
|
7
|
+
await new Promise((r) => setTimeout(r, 1500 * 2 ** (attempt - 1)));
|
|
8
|
+
const result = await run("gh", args, { input });
|
|
9
|
+
if (result.code === 0)
|
|
10
|
+
return result.stdout;
|
|
11
|
+
lastError = (result.stderr || result.stdout).trim();
|
|
12
|
+
if (!TRANSIENT.test(lastError))
|
|
13
|
+
break;
|
|
14
|
+
}
|
|
15
|
+
throw new Error(`gh ${args.slice(0, 4).join(" ")} failed: ${lastError.split("\n").slice(-3).join(" ")}`);
|
|
16
|
+
}
|
|
17
|
+
export class GitHub {
|
|
18
|
+
owner;
|
|
19
|
+
repo;
|
|
20
|
+
opts;
|
|
21
|
+
constructor(owner, repo, opts = {}) {
|
|
22
|
+
this.owner = owner;
|
|
23
|
+
this.repo = repo;
|
|
24
|
+
this.opts = opts;
|
|
25
|
+
}
|
|
26
|
+
get dryRun() {
|
|
27
|
+
return Boolean(this.opts.dryRun);
|
|
28
|
+
}
|
|
29
|
+
repoPath(path) {
|
|
30
|
+
return path.startsWith("/") ? path.slice(1) : `repos/${this.owner}/${this.repo}/${path}`;
|
|
31
|
+
}
|
|
32
|
+
async get(path) {
|
|
33
|
+
return JSON.parse(await gh(["api", this.repoPath(path)]));
|
|
34
|
+
}
|
|
35
|
+
/** Who this token belongs to. App and workflow tokens aren't a person, so GitHub refuses and this is null. */
|
|
36
|
+
async viewer() {
|
|
37
|
+
return this.get("/user").then((u) => u.login, () => null);
|
|
38
|
+
}
|
|
39
|
+
/** All pages of a list endpoint, flattened. */
|
|
40
|
+
async list(path) {
|
|
41
|
+
const sep = path.includes("?") ? "&" : "?";
|
|
42
|
+
const out = await gh(["api", "--paginate", "--slurp", `${this.repoPath(path)}${sep}per_page=100`]);
|
|
43
|
+
return JSON.parse(out).flat();
|
|
44
|
+
}
|
|
45
|
+
async write(method, path, body) {
|
|
46
|
+
if (this.opts.dryRun) {
|
|
47
|
+
this.opts.log?.(`[dry run] ${method} ${this.repoPath(path)}\n${JSON.stringify(body, null, 2)}`);
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const out = await gh(["api", "-X", method, this.repoPath(path), "--input", "-"], JSON.stringify(body));
|
|
51
|
+
return (out.trim() ? JSON.parse(out) : null);
|
|
52
|
+
}
|
|
53
|
+
async graphql(query, variables, mutation = false) {
|
|
54
|
+
if (mutation && this.opts.dryRun) {
|
|
55
|
+
this.opts.log?.(`[dry run] graphql ${query.replace(/\s+/g, " ").slice(0, 80)} ${JSON.stringify(variables)}`);
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
const args = ["api", "graphql", "-f", `query=${query}`];
|
|
59
|
+
for (const [k, v] of Object.entries(variables))
|
|
60
|
+
args.push(typeof v === "number" ? "-F" : "-f", `${k}=${v}`);
|
|
61
|
+
return JSON.parse(await gh(args)).data;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { trustedComment } from "./handled.js";
|
|
2
|
+
import { FINDING_MARKER_RE } from "./markdown.js";
|
|
3
|
+
/** Older reviews answered a fixed thread with a reply carrying this marker. */
|
|
4
|
+
const GONE_MARKER = "<!-- mergelight:gone -->";
|
|
5
|
+
/** Someone reopened a thread Mergelight closed. It stays open until a person resolves it again. */
|
|
6
|
+
const REOPENED_MARKER = "<!-- mergelight:reopened -->";
|
|
7
|
+
const CLOSED_RE = /<!-- mergelight:closed how=(fixed|resolved) resolved=([01])(?: sha=([a-f0-9]+))? -->/;
|
|
8
|
+
const SUMMARY_END = "</summary>\n\n";
|
|
9
|
+
const DETAILS_END = "\n\n</details>";
|
|
10
|
+
export function readClosed(body) {
|
|
11
|
+
const m = body.match(CLOSED_RE);
|
|
12
|
+
return m ? { how: m[1], resolved: m[2] === "1", sha: m[3] ?? null } : null;
|
|
13
|
+
}
|
|
14
|
+
/** The comment with a checkmark on top and the original behind a dropdown, named after the finding. */
|
|
15
|
+
export function closedBody(body, c) {
|
|
16
|
+
const marker = body.match(FINDING_MARKER_RE)?.[0] ?? "";
|
|
17
|
+
const original = body.replace(FINDING_MARKER_RE, "").replace(REOPENED_MARKER, "").trim();
|
|
18
|
+
const label = (original.split("\n")[0] ?? "Original comment").replace(/\*\*/g, "").replace(/</g, "<");
|
|
19
|
+
const why = c.how === "fixed"
|
|
20
|
+
? `The code changed and Mergelight no longer finds this${c.sha ? ` in \`${c.sha}\`` : ""}.`
|
|
21
|
+
: `Resolved${c.by ? ` by ${c.by}` : ""}.`;
|
|
22
|
+
return [
|
|
23
|
+
marker,
|
|
24
|
+
`<!-- mergelight:closed how=${c.how} resolved=${c.resolved ? 1 : 0}${c.sha ? ` sha=${c.sha}` : ""} -->`,
|
|
25
|
+
`✅ **Handled.** ${why}`,
|
|
26
|
+
"",
|
|
27
|
+
`<details><summary>${label}${SUMMARY_END}${original}${DETAILS_END}`,
|
|
28
|
+
].join("\n");
|
|
29
|
+
}
|
|
30
|
+
/** Back to the original comment. */
|
|
31
|
+
export function reopenedBody(body, keepOpen) {
|
|
32
|
+
const marker = body.match(FINDING_MARKER_RE)?.[0] ?? "";
|
|
33
|
+
const start = body.indexOf(SUMMARY_END);
|
|
34
|
+
const end = body.lastIndexOf(DETAILS_END);
|
|
35
|
+
const original = start >= 0 && end > start ? body.slice(start + SUMMARY_END.length, end) : body;
|
|
36
|
+
return [marker, ...(keepOpen ? [REOPENED_MARKER] : []), original].join("\n");
|
|
37
|
+
}
|
|
38
|
+
/** The finding a thread is about, if it's one of Mergelight's own. */
|
|
39
|
+
export function threadFinding(t) {
|
|
40
|
+
const first = t.comments.nodes[0];
|
|
41
|
+
if (!first)
|
|
42
|
+
return null;
|
|
43
|
+
if (!trustedComment({ user: { type: first.author?.__typename }, author_association: first.authorAssociation }))
|
|
44
|
+
return null;
|
|
45
|
+
const id = first.body.match(FINDING_MARKER_RE)?.[1];
|
|
46
|
+
return id ? { id, commentId: first.databaseId, body: first.body } : null;
|
|
47
|
+
}
|
|
48
|
+
/** What this round should do to a thread, given the findings the review still reports. */
|
|
49
|
+
export function threadAction(t, open) {
|
|
50
|
+
const found = threadFinding(t);
|
|
51
|
+
if (!found)
|
|
52
|
+
return null;
|
|
53
|
+
const closed = readClosed(found.body);
|
|
54
|
+
const answeredBefore = t.comments.nodes.some((c) => c.body.includes(GONE_MARKER));
|
|
55
|
+
if (closed) {
|
|
56
|
+
if (open.has(found.id))
|
|
57
|
+
return { kind: "regressed", unresolve: closed.how === "fixed" && t.isResolved };
|
|
58
|
+
// resolved=0 means GitHub wouldn't let the workflow resolve it, so an open thread doesn't mean anyone reopened it.
|
|
59
|
+
return !t.isResolved && closed.resolved ? { kind: "reopened" } : null;
|
|
60
|
+
}
|
|
61
|
+
if (t.isResolved) {
|
|
62
|
+
if (open.has(found.id))
|
|
63
|
+
return null;
|
|
64
|
+
return answeredBefore ? { kind: "fixed", resolve: false } : { kind: "resolved" };
|
|
65
|
+
}
|
|
66
|
+
if (answeredBefore || found.body.includes(REOPENED_MARKER))
|
|
67
|
+
return null;
|
|
68
|
+
return t.isOutdated && !open.has(found.id) ? { kind: "fixed", resolve: true } : null;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Findings whose thread someone with write access resolved, with who did it. The
|
|
72
|
+
* verifier hears about these as a team decision, so a pull request's own author
|
|
73
|
+
* can't talk it out of a finding: GitHub lets them resolve threads too.
|
|
74
|
+
*/
|
|
75
|
+
export async function resolvedByPeople(threads, canWrite) {
|
|
76
|
+
const out = new Map();
|
|
77
|
+
for (const t of threads) {
|
|
78
|
+
const found = threadFinding(t);
|
|
79
|
+
const by = t.resolvedBy?.login;
|
|
80
|
+
if (!found || !t.isResolved || !by)
|
|
81
|
+
continue;
|
|
82
|
+
if (readClosed(found.body)?.how === "fixed" || t.comments.nodes.some((c) => c.body.includes(GONE_MARKER)))
|
|
83
|
+
continue;
|
|
84
|
+
if (await canWrite(by))
|
|
85
|
+
out.set(found.id, by);
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export function parsePatch(patch) {
|
|
2
|
+
const hunks = [];
|
|
3
|
+
let current = null;
|
|
4
|
+
let right = 0;
|
|
5
|
+
for (const line of patch.split("\n")) {
|
|
6
|
+
const header = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
|
7
|
+
if (header) {
|
|
8
|
+
right = Number(header[1]);
|
|
9
|
+
current = { start: right, end: right - 1, lines: new Set() };
|
|
10
|
+
hunks.push(current);
|
|
11
|
+
continue;
|
|
12
|
+
}
|
|
13
|
+
if (!current || line.startsWith("\\"))
|
|
14
|
+
continue;
|
|
15
|
+
if (line.startsWith("-"))
|
|
16
|
+
continue;
|
|
17
|
+
// Context and added lines both exist on the right side.
|
|
18
|
+
current.lines.add(right);
|
|
19
|
+
current.end = right;
|
|
20
|
+
right++;
|
|
21
|
+
}
|
|
22
|
+
return hunks.filter((h) => h.lines.size > 0);
|
|
23
|
+
}
|
|
24
|
+
export async function commentableLines(api, number) {
|
|
25
|
+
const files = await api.list(`pulls/${number}/files`);
|
|
26
|
+
const map = new Map();
|
|
27
|
+
for (const f of files)
|
|
28
|
+
if (f.patch)
|
|
29
|
+
map.set(f.filename, parsePatch(f.patch));
|
|
30
|
+
return map;
|
|
31
|
+
}
|
|
32
|
+
/** Where to put a finding's inline comment, or null if its lines aren't in the diff. */
|
|
33
|
+
export function place(map, file, line, endLine) {
|
|
34
|
+
const hunks = map.get(file);
|
|
35
|
+
if (!hunks)
|
|
36
|
+
return null;
|
|
37
|
+
const lo = Math.min(line, endLine);
|
|
38
|
+
const hi = Math.max(line, endLine);
|
|
39
|
+
for (const h of hunks) {
|
|
40
|
+
if (h.lines.has(lo) && h.lines.has(hi))
|
|
41
|
+
return hi > lo ? { start_line: lo, line: hi } : { line: hi };
|
|
42
|
+
}
|
|
43
|
+
// Fall back to the nearest commentable line inside the finding's range.
|
|
44
|
+
for (const h of hunks) {
|
|
45
|
+
for (let l = hi; l >= lo; l--)
|
|
46
|
+
if (h.lines.has(l))
|
|
47
|
+
return { line: l };
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether Mergelight's hidden markers in this comment count. Anyone can write a
|
|
3
|
+
* comment containing them, and they steer what gets posted and what the verifier
|
|
4
|
+
* reads, so a passer-by's comment must not be taken for ours.
|
|
5
|
+
*/
|
|
6
|
+
export function trustedComment(c) {
|
|
7
|
+
return c.user?.type === "Bot" || ["OWNER", "MEMBER", "COLLABORATOR"].includes(c.author_association ?? "");
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Who can write to the repository. A workflow token sees a private org member as
|
|
11
|
+
* CONTRIBUTOR, so the association alone would silently drop their marks.
|
|
12
|
+
*/
|
|
13
|
+
export function writeAccess(api) {
|
|
14
|
+
const ask = askWriteAccess(api);
|
|
15
|
+
return async (login) => (await ask(login)) === true;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The same, but null when GitHub couldn't be asked: an error, or a login that may not see
|
|
19
|
+
* permissions, which GitHub refuses to anyone who can't push.
|
|
20
|
+
*/
|
|
21
|
+
export function askWriteAccess(api) {
|
|
22
|
+
const known = new Map();
|
|
23
|
+
return (login) => {
|
|
24
|
+
let answer = known.get(login);
|
|
25
|
+
if (!answer) {
|
|
26
|
+
answer = api
|
|
27
|
+
.get(`collaborators/${encodeURIComponent(login)}/permission`)
|
|
28
|
+
.then((r) => r.permission === "admin" || r.permission === "write")
|
|
29
|
+
.catch(() => null);
|
|
30
|
+
known.set(login, answer);
|
|
31
|
+
}
|
|
32
|
+
return answer;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const MARK_RE = /<!-- mergelight:handled:v1 ([A-Za-z0-9+/=]+) -->/;
|
|
36
|
+
export const MAX_NOTE = 1000;
|
|
37
|
+
export function encodeMark(ids, as, note, sha) {
|
|
38
|
+
return `<!-- mergelight:handled:v1 ${Buffer.from(JSON.stringify({ ids, as, note, sha })).toString("base64")} -->`;
|
|
39
|
+
}
|
|
40
|
+
export function decodeMark(body) {
|
|
41
|
+
const m = body?.match(MARK_RE);
|
|
42
|
+
if (!m)
|
|
43
|
+
return null;
|
|
44
|
+
try {
|
|
45
|
+
const { ids, as, note, sha } = JSON.parse(Buffer.from(m[1], "base64").toString("utf8"));
|
|
46
|
+
if (!Array.isArray(ids) || (as !== "fixed" && as !== "wont_fix"))
|
|
47
|
+
return null;
|
|
48
|
+
return {
|
|
49
|
+
ids: ids.filter((id) => typeof id === "string" && /^[a-f0-9]+$/.test(id)),
|
|
50
|
+
as,
|
|
51
|
+
note: typeof note === "string" ? note.slice(0, MAX_NOTE) : null,
|
|
52
|
+
sha: typeof sha === "string" ? sha : null,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The latest mark per finding, from comments by people who can write to the repository.
|
|
61
|
+
* A person's association isn't enough: MEMBER means a member of the org, who may only be able to read
|
|
62
|
+
* this repository, and a won't-fix mark tells the verifier the team decided. So every person is asked
|
|
63
|
+
* about. Bots are the exception: one can only comment where it was installed.
|
|
64
|
+
*/
|
|
65
|
+
export async function readMarks(comments, canWrite) {
|
|
66
|
+
const marked = comments
|
|
67
|
+
.map((comment) => ({ comment, mark: decodeMark(comment.body) }))
|
|
68
|
+
.filter((c) => c.mark)
|
|
69
|
+
.sort((a, b) => Date.parse(a.comment.created_at ?? "") - Date.parse(b.comment.created_at ?? ""));
|
|
70
|
+
const marks = new Map();
|
|
71
|
+
for (const { comment, mark } of marked) {
|
|
72
|
+
const by = comment.user?.login ?? "";
|
|
73
|
+
if (comment.user?.type !== "Bot") {
|
|
74
|
+
const can = by ? await canWrite(by) : false;
|
|
75
|
+
// When GitHub can't be asked, the association is all there is. A failed lookup must not throw
|
|
76
|
+
// away the team's decisions; only GitHub's answer that the person can't push does.
|
|
77
|
+
if (can === false || (can === null && !trustedComment(comment)))
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
for (const id of mark.ids) {
|
|
81
|
+
marks.set(id, { id, as: mark.as, note: mark.note, sha: mark.sha, by, at: comment.created_at ?? "", url: comment.html_url });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return marks;
|
|
85
|
+
}
|
|
86
|
+
export function findingState(f, mark, lastReviewAt) {
|
|
87
|
+
if (mark?.as === "wont_fix")
|
|
88
|
+
return "wont_fix";
|
|
89
|
+
if (f.status === "gone")
|
|
90
|
+
return "gone";
|
|
91
|
+
if (!mark)
|
|
92
|
+
return "open";
|
|
93
|
+
return markedSince(mark, lastReviewAt) ? "fix_pending" : "still_found";
|
|
94
|
+
}
|
|
95
|
+
/** True if the latest review published before this mark, so it can't have taken it into account. */
|
|
96
|
+
export function markedSince(mark, lastReviewAt) {
|
|
97
|
+
return !lastReviewAt || Date.parse(mark.at) > Date.parse(lastReviewAt);
|
|
98
|
+
}
|