@mergelight/cli 0.1.18 → 0.1.19
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/cli.js +176 -18
- package/dist/cloud.js +3 -2
- package/dist/connect-claude.js +17 -4
- package/dist/connect.js +363 -50
- package/dist/github.js +5 -0
- package/dist/jobs-command.js +182 -0
- package/dist/jobs.js +437 -0
- package/dist/prompt.js +26 -5
- package/dist/providers/claude.js +25 -5
- package/dist/providers/codex.js +280 -11
- package/dist/publish/api.js +4 -2
- package/dist/publish/closed.js +1 -1
- package/dist/publish/markdown.js +100 -5
- package/dist/publish/publish.js +106 -19
- package/dist/publish/state.js +2 -1
- package/dist/push-jobs.js +381 -0
- package/dist/render.js +5 -0
- package/dist/repo-rules.js +62 -19
- package/dist/review.js +65 -20
- package/dist/run-jobs.js +522 -0
- package/dist/schema.js +5 -0
- package/dist/setup.js +11 -7
- package/dist/types.js +6 -1
- package/dist/workspace.js +457 -21
- package/package.json +1 -1
- package/scripts/refresh-login.mjs +123 -2
- package/scripts/save-login.sh +2 -0
- package/templates/mergelight-jobs.yml +125 -0
package/dist/connect.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
2
|
+
import { appendFileSync, readFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { FAILED_MARKER, PENDING_MARKER, pendingSummaryBody, SUMMARY_MARKER } from "./publish/markdown.js";
|
|
5
|
-
import { CHECK_FAILED_TITLE, readPrReviewState, writeCheck } from "./publish/publish.js";
|
|
5
|
+
import { CHECK_FAILED_TITLE, readPrReviewState, syncApproval, UNREVIEWED, writeCheck } from "./publish/publish.js";
|
|
6
6
|
import { stateBlock } from "./publish/state.js";
|
|
7
7
|
import { claudeCodeRef, readCodeRef, shareClaudeToken, startClaudeSignIn, waitForPastedCode } from "./connect-claude.js";
|
|
8
8
|
/**
|
|
@@ -14,6 +14,8 @@ import { claudeCodeRef, readCodeRef, shareClaudeToken, startClaudeSignIn, waitFo
|
|
|
14
14
|
*/
|
|
15
15
|
/** Codex says the code lasts 15 minutes. */
|
|
16
16
|
export const LOGIN_TIMEOUT_MS = 16 * 60_000;
|
|
17
|
+
/** How long a checker's prompt waits for Claude's code: the 15 minutes the comment promises. */
|
|
18
|
+
const CHECK_WAIT_MS = 15 * 60_000;
|
|
17
19
|
export const INSTALL_URL = "https://github.com/apps/mergelight-ai/installations/new";
|
|
18
20
|
export const CHATGPT_SECURITY_URL = "https://chatgpt.com/settings/security";
|
|
19
21
|
/**
|
|
@@ -47,8 +49,10 @@ export function connectedBody(account, secretName) {
|
|
|
47
49
|
return `🔌 Reviews on this repository now use ${who}. If that isn't yours, remove the \`${secretName}\` secret and push a commit to connect again.`;
|
|
48
50
|
}
|
|
49
51
|
/** The setup page reads the link and code from this hidden line, so a change to how the comment looks can't break it. */
|
|
50
|
-
export function connectData(login, claudeUrl) {
|
|
51
|
-
|
|
52
|
+
export function connectData(login, claudeUrl, purpose) {
|
|
53
|
+
// "for" is only there for a checker's login, so the page can say what it connects.
|
|
54
|
+
const data = { url: login?.url ?? "", code: login?.code ?? "", claudeUrl: claudeUrl ?? null, ...(purpose ? { for: purpose } : {}) };
|
|
55
|
+
return `<!-- mergelight:connect:v1 ${JSON.stringify(data).replace(/--/g, "\\u002d\\u002d")} -->`;
|
|
52
56
|
}
|
|
53
57
|
const SETUP_URL = "https://mergelight.dev/setup/";
|
|
54
58
|
/** Opens the setup page on the step this pull request is waiting for. */
|
|
@@ -80,16 +84,58 @@ export function connectBody(login, runUrl, claudeUrl, setupLink = SETUP_URL) {
|
|
|
80
84
|
`<sub>Reviews use the plan of whoever connects it, so only do this if you're setting up this repository. This comes from ${run}. The login is saved as this repository's secret and never reaches Mergelight.</sub>`,
|
|
81
85
|
].join("\n");
|
|
82
86
|
}
|
|
83
|
-
|
|
87
|
+
/** The name a person signs in with: ChatGPT for Codex. */
|
|
88
|
+
export function loginName(ai) {
|
|
89
|
+
return ai === "codex" ? "ChatGPT" : "Claude";
|
|
90
|
+
}
|
|
91
|
+
/** The name of the AI that does the work. */
|
|
92
|
+
export function aiName(ai) {
|
|
93
|
+
return ai === "codex" ? "Codex" : "Claude";
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The comment that asks to connect the AI that checks the review. The review doesn't wait for it longer
|
|
97
|
+
* than the code lasts: without it, the reviewer's own AI checks, and the summary says so.
|
|
98
|
+
*/
|
|
99
|
+
export function connectCheckBody(ai, reviewer, login, runUrl, claudeUrl, setupLink = SETUP_URL) {
|
|
100
|
+
const steps = ai === "codex" ? (login ? `[Open ChatGPT](${login.url}) and enter \`${login.code}\`` : null) : claudeUrl ? `[Connect on mergelight.dev](${setupLink})` : null;
|
|
101
|
+
const run = runUrl ? `[your own GitHub Actions run](${runUrl})` : "your own GitHub Actions run";
|
|
102
|
+
return [
|
|
103
|
+
SUMMARY_MARKER,
|
|
104
|
+
PENDING_MARKER,
|
|
105
|
+
connectData(ai === "codex" ? login : null, ai === "claude" ? claudeUrl : undefined, "check"),
|
|
106
|
+
`### 🔌 Connect ${loginName(ai)} to check this review`,
|
|
107
|
+
"",
|
|
108
|
+
`${steps ?? "Follow the steps on mergelight.dev/setup"}. ${aiName(reviewer)}'s review then starts by itself, and ${aiName(ai)} checks its findings.`,
|
|
109
|
+
"",
|
|
110
|
+
`If nobody connects it within 15 minutes, the review starts anyway, checked by ${aiName(reviewer)}.`,
|
|
111
|
+
"",
|
|
112
|
+
"<details><summary>Something not working?</summary>",
|
|
113
|
+
"",
|
|
114
|
+
`- **The ${ai === "codex" ? "code" : "link"} ran out:** it lasts 15 minutes. Push a new commit to get a new one.`,
|
|
115
|
+
...(ai === "codex" ? [`- **OpenAI refuses the code:** turn on "Enable device code sign-in" in your [ChatGPT security settings](${CHATGPT_SECURITY_URL}), or ask your workspace admin to.`] : []),
|
|
116
|
+
"",
|
|
117
|
+
"</details>",
|
|
118
|
+
"",
|
|
119
|
+
`<sub>Checks use the plan of whoever connects it, so only do this if you're setting up this repository. This comes from ${run}. The login is saved as this repository's secret and never reaches Mergelight.</sub>`,
|
|
120
|
+
].join("\n");
|
|
121
|
+
}
|
|
122
|
+
/** The waiting check's title while the checker's login is asked for. */
|
|
123
|
+
export function checkWaitingTitle(ai) {
|
|
124
|
+
return `Waiting for you to connect ${loginName(ai)} to check the review`;
|
|
125
|
+
}
|
|
126
|
+
export function installAppBody(login = "ChatGPT") {
|
|
84
127
|
return [
|
|
85
128
|
SUMMARY_MARKER,
|
|
86
129
|
PENDING_MARKER,
|
|
87
130
|
"### 🔌 One step left: install the Mergelight AI app",
|
|
88
131
|
"",
|
|
89
|
-
`[Install it on this repository](${INSTALL_URL}), or approve its updated permissions if it's already installed, then push a new commit. The app saves your
|
|
132
|
+
`[Install it on this repository](${INSTALL_URL}), or approve its updated permissions if it's already installed, then push a new commit. The app saves your ${login} login, so you only connect once.`,
|
|
90
133
|
].join("\n");
|
|
91
134
|
}
|
|
92
|
-
export function connectFailedBody(reason, claudeOffered = false) {
|
|
135
|
+
export function connectFailedBody(reason, claudeOffered = false, onlyClaude = false) {
|
|
136
|
+
if (onlyClaude) {
|
|
137
|
+
return [SUMMARY_MARKER, FAILED_MARKER, "### ⚠️ Mergelight couldn't connect to Claude", "", reason, "", "Push a new commit to get a new link. You can also use an Anthropic API key instead: https://mergelight.dev/setup"].join("\n");
|
|
138
|
+
}
|
|
93
139
|
return [
|
|
94
140
|
SUMMARY_MARKER,
|
|
95
141
|
FAILED_MARKER,
|
|
@@ -159,22 +205,42 @@ export async function connect(deps) {
|
|
|
159
205
|
await deps.connected(winner);
|
|
160
206
|
return 0;
|
|
161
207
|
}
|
|
162
|
-
await deps.failed(claude
|
|
163
|
-
?
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
208
|
+
await deps.failed(deps.only === "claude"
|
|
209
|
+
? claude
|
|
210
|
+
? "The Claude link ran out before anyone finished signing in."
|
|
211
|
+
: (deps.claudeUnavailable?.() ?? "Claude's sign-in couldn't start on this run.")
|
|
212
|
+
: claude
|
|
213
|
+
? "The ChatGPT code and the Claude link both ran out before anyone finished signing in."
|
|
214
|
+
: !shown && deps.chatgptUnavailable?.()
|
|
215
|
+
? deps.chatgptUnavailable()
|
|
216
|
+
: shown
|
|
217
|
+
? `The code ran out, or OpenAI refused it. Check that "Enable device code sign-in" is on in your [ChatGPT security settings](${CHATGPT_SECURITY_URL}).`
|
|
218
|
+
: `Codex couldn't start a device login. "Enable device code sign-in" may be off in your [ChatGPT security settings](${CHATGPT_SECURITY_URL}), or for your workspace.`);
|
|
167
219
|
return 1;
|
|
168
220
|
}
|
|
169
221
|
/** Tells the pull request the app has to be installed first. There's nowhere to save a login without it. */
|
|
170
|
-
export async function askForApp(api, number, headSha) {
|
|
171
|
-
await upsertSummary(api, number, installAppBody());
|
|
222
|
+
export async function askForApp(api, number, headSha, login = "ChatGPT") {
|
|
223
|
+
await upsertSummary(api, number, installAppBody(login));
|
|
172
224
|
await writeCheck(api, null, headSha, {
|
|
173
225
|
status: "completed",
|
|
174
226
|
conclusion: "neutral",
|
|
175
227
|
completed_at: new Date().toISOString(),
|
|
176
228
|
output: { title: "Install the Mergelight AI app", summary: `Install it, then push a new commit: ${INSTALL_URL}` },
|
|
177
229
|
});
|
|
230
|
+
await takeBackOlderApprovals(api, number, headSha);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* No review runs for this commit: an approval Mergelight gave an earlier one must not count for it, next
|
|
234
|
+
* to a check that a branch rule takes for passed. Only while this commit is still the newest: a newer run
|
|
235
|
+
* may have reviewed and approved the newest one meanwhile. One that can't be read is taken for the
|
|
236
|
+
* newest, as a merge can't be taken back.
|
|
237
|
+
*/
|
|
238
|
+
async function takeBackOlderApprovals(api, number, headSha, log = () => { }) {
|
|
239
|
+
const newest = await (async () => (await api.get(`pulls/${number}`)).head.sha)().catch(() => headSha);
|
|
240
|
+
if (newest === headSha)
|
|
241
|
+
await syncApproval(api, number, "yellow", headSha, log, { why: UNREVIEWED, otherCommitsOnly: true });
|
|
242
|
+
else
|
|
243
|
+
log(`A newer commit (${newest.slice(0, 7)}) has its own run, so Mergelight's approvals are left to it.`);
|
|
178
244
|
}
|
|
179
245
|
/** The summary holds what earlier rounds found, so a login prompt on a reviewed pull request has to keep that. */
|
|
180
246
|
async function upsertSummary(api, number, body) {
|
|
@@ -189,27 +255,171 @@ export function withState(body, previous) {
|
|
|
189
255
|
return state ? `${body}\n${state}` : body;
|
|
190
256
|
}
|
|
191
257
|
/** The real thing: Codex on this runner, and the pull request as the place to show the code. */
|
|
192
|
-
/**
|
|
193
|
-
|
|
258
|
+
/**
|
|
259
|
+
* Whether the workflow passes a Claude login on to Mergelight. A repository set up before Claude support
|
|
260
|
+
* doesn't, so connecting Claude there would only ask again next time: "no". A workflow that calls a
|
|
261
|
+
* reusable one may pass it on in a file this can't tell, and one that can't be read can't say: "unknown".
|
|
262
|
+
*/
|
|
263
|
+
export function claudeInWorkflow(text, input = "claude-code-oauth-token", job, secret, forCheck = false) {
|
|
264
|
+
if (text === null)
|
|
265
|
+
return "unknown";
|
|
266
|
+
// Lines that are code, not comments: a line commented out passes nothing on.
|
|
267
|
+
let lines = text.split("\n").map((line) => line.replace(/(^|\s)#.*$/, ""));
|
|
268
|
+
const indent = (line) => line.match(/^\s*/)[0].length;
|
|
269
|
+
// Only this run's job: an input another job passes on doesn't reach this one.
|
|
270
|
+
if (job) {
|
|
271
|
+
// The job's key, right under jobs:, with an anchor after it or not (review: &review): never a
|
|
272
|
+
// workflow input or anything else of that name. One that can't be found can't be told.
|
|
273
|
+
const jobsAt = lines.findIndex((line) => /^["']?jobs["']?\s*:\s*$/.test(line));
|
|
274
|
+
if (jobsAt < 0)
|
|
275
|
+
return "unknown";
|
|
276
|
+
let jobsEnd = jobsAt + 1;
|
|
277
|
+
while (jobsEnd < lines.length && (!lines[jobsEnd].trim() || indent(lines[jobsEnd]) > 0))
|
|
278
|
+
jobsEnd++;
|
|
279
|
+
const childIndent = lines.slice(jobsAt + 1, jobsEnd).find((l) => l.trim())?.match(/^\s*/)?.[0].length ?? 2;
|
|
280
|
+
const keyRe = new RegExp(`^\\s{${childIndent}}["']?${job.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']?\\s*:\\s*(?:&[\\w-]+\\s*)?$`);
|
|
281
|
+
const found = lines.slice(jobsAt + 1, jobsEnd).findIndex((line) => keyRe.test(line));
|
|
282
|
+
if (found < 0)
|
|
283
|
+
return "unknown";
|
|
284
|
+
const at = jobsAt + 1 + found;
|
|
285
|
+
let end = at + 1;
|
|
286
|
+
while (end < lines.length && (!lines[end].trim() || indent(lines[end]) > indent(lines[at])))
|
|
287
|
+
end++;
|
|
288
|
+
lines = lines.slice(at, end);
|
|
289
|
+
}
|
|
290
|
+
// Each step that uses Mergelight itself, or a fork of it (a repository named mergelight), from its "-" on.
|
|
291
|
+
const steps = [];
|
|
292
|
+
lines.forEach((line, i) => {
|
|
293
|
+
if (!/^\s*(?:-\s*)?uses:\s*["']?[^\s"'/]+\/mergelight@/i.test(line))
|
|
294
|
+
return;
|
|
295
|
+
let start = i;
|
|
296
|
+
while (start > 0 && !/^\s*-\s/.test(lines[start]))
|
|
297
|
+
start--;
|
|
298
|
+
const dash = indent(lines[start]);
|
|
299
|
+
let end = start + 1;
|
|
300
|
+
while (end < lines.length && (!lines[end].trim() || indent(lines[end]) > dash))
|
|
301
|
+
end++;
|
|
302
|
+
const step = lines.slice(start, end).join("\n");
|
|
303
|
+
// A step that runs only when someone approves needs no AI login: it only turns the check green. Its
|
|
304
|
+
// condition can go on over the lines below "if:", as with "if: >-".
|
|
305
|
+
const ifAt = lines.slice(start, end).findIndex((l) => /^\s*(?:-\s*)?if:/.test(l));
|
|
306
|
+
let condition = "";
|
|
307
|
+
if (ifAt >= 0) {
|
|
308
|
+
const own = start + ifAt;
|
|
309
|
+
let last = own + 1;
|
|
310
|
+
while (last < end && (!lines[last].trim() || indent(lines[last]) > indent(lines[own].replace(/-\s*/, " "))))
|
|
311
|
+
last++;
|
|
312
|
+
condition = lines.slice(own, last).join(" ");
|
|
313
|
+
}
|
|
314
|
+
// Likewise a step that runs only on other events, such as a schedule: every event its condition names
|
|
315
|
+
// with == is one a pull request never starts, so it never runs where a login is connected.
|
|
316
|
+
// Only comparisons of the event's name count, never a branch's or anything else's. Each part on its
|
|
317
|
+
// own side of || must name such an event: a part without one could run on a pull request.
|
|
318
|
+
// So is a step that runs only for a review someone submitted, as when its condition compares
|
|
319
|
+
// github.event.review.state with a word: a pull request's event has no review, so that is never true.
|
|
320
|
+
const pullRequest = new Set(["pull_request", "pull_request_target"]);
|
|
321
|
+
const parts = condition.replace(/^\s*(?:-\s*)?if:\s*[>|]?[-+]?/, "").replace(/\$\{\{|\}\}/g, " ").split("||");
|
|
322
|
+
const otherEventOnly = (part) => {
|
|
323
|
+
// A group with ! before it turns what is inside around: it can't be told.
|
|
324
|
+
if (/!\s*\(/.test(part))
|
|
325
|
+
return false;
|
|
326
|
+
const terms = part.replace(/[()]/g, " ").split("&&");
|
|
327
|
+
const named = [...part.matchAll(/event_name\s*==\s*["']([\w-]+)["']/g)].map((m) => m[1]);
|
|
328
|
+
if (named.length > 0 && named.every((e) => !pullRequest.has(e)))
|
|
329
|
+
return true;
|
|
330
|
+
return terms.some((t) => /^\s*github\.event\.review\.[\w.]+\s*==\s*["'][^"']*[A-Za-z][^"']*["']\s*$/.test(t));
|
|
331
|
+
};
|
|
332
|
+
if (condition && parts.every(otherEventOnly))
|
|
333
|
+
return;
|
|
334
|
+
// A step that only runs the jobs never checks a review: for the checker's login it doesn't count.
|
|
335
|
+
if (forCheck && /^\s*["']?run["']?\s*:\s*["']?jobs["']?\s*$/m.test(step))
|
|
336
|
+
return;
|
|
337
|
+
steps.push(step);
|
|
338
|
+
});
|
|
339
|
+
// A reusable workflow or a composite action of the team's own may pass the login on in a file this
|
|
340
|
+
// can't see: unless Mergelight is used here in plain sight, it can't say. Nor through YAML's shared
|
|
341
|
+
// parts (an alias like *inputs, or a << merge), which this doesn't follow.
|
|
342
|
+
if (!steps.length || steps.some((step) => /(^|[\s:{,\[])\*[\w-]+|<<\s*:/m.test(step)))
|
|
343
|
+
return "unknown";
|
|
344
|
+
// The name may be quoted, or in a flow mapping, as YAML allows. Every Mergelight step of this job must
|
|
345
|
+
// pass it on: which one runs now can't be told from here, and a login saved for a step that doesn't
|
|
346
|
+
// pass it on would replace the one another step uses. The message then says what to add.
|
|
347
|
+
// And from the secret the login is saved to: a login saved as CLAUDE_CODE_OAUTH_TOKEN never reaches
|
|
348
|
+
// a step that reads another secret.
|
|
349
|
+
const passes = (step) => {
|
|
350
|
+
// Spaces only after the colon: a value left empty mustn't take the next line for its own.
|
|
351
|
+
const found = new RegExp(`(?:^|[\\s{,])["']?${input}["']?[ \\t]*:[ \\t]*([^\\n,}]*)`, "m").exec(step);
|
|
352
|
+
if (!found)
|
|
353
|
+
return false;
|
|
354
|
+
let value = found[1].trim();
|
|
355
|
+
// A value goes on over the lines below that are set in further than its name, as YAML reads it: after
|
|
356
|
+
// >- or |, those lines are the value; after anything else, they carry it on, as with "${{" alone on
|
|
357
|
+
// the first line.
|
|
358
|
+
const rest = step.slice(found.index + found[0].length).split("\n").slice(1);
|
|
359
|
+
const own = indent(step.slice(0, found.index + found[0].length).split("\n").pop());
|
|
360
|
+
const more = [];
|
|
361
|
+
for (const l of rest) {
|
|
362
|
+
if (l.trim() && indent(l) <= own)
|
|
363
|
+
break;
|
|
364
|
+
more.push(l.trim());
|
|
365
|
+
}
|
|
366
|
+
value = (/^[>|][-+0-9]*$/.test(value) ? more : [value, ...more]).join(" ").trim();
|
|
367
|
+
// An empty value passes nothing on: a login saved now would never reach a later run.
|
|
368
|
+
if (!value || /^(["'])\1$/.test(value) || value === "~" || value === "null")
|
|
369
|
+
return false;
|
|
370
|
+
// secrets.NAME or secrets['NAME'], in any letter case, as GitHub reads secret names. With a fallback,
|
|
371
|
+
// like secrets.A || secrets.B, one of them being the secret is enough.
|
|
372
|
+
const named = [...value.matchAll(/secrets(?:\.([A-Za-z0-9_]+)|\[\s*["']([A-Za-z0-9_]+)["']\s*\])/gi)].map((m) => (m[1] ?? m[2]).toUpperCase());
|
|
373
|
+
return !secret || !named.length || named.includes(secret.toUpperCase());
|
|
374
|
+
};
|
|
375
|
+
return steps.every(passes) ? "yes" : "no";
|
|
376
|
+
}
|
|
377
|
+
/** How long reading the workflow file may take before it counts as one that can't be read. */
|
|
378
|
+
const WORKFLOW_READ_MS = 60_000;
|
|
379
|
+
async function workflowHasClaude(api, env, input = "claude-code-oauth-token", secret = "CLAUDE_CODE_OAUTH_TOKEN", forCheck = false) {
|
|
194
380
|
const [, path, ref] = (env.GITHUB_WORKFLOW_REF ?? "").match(/^[^/]+\/[^/]+\/(.+?)@(.+)$/) ?? [];
|
|
195
381
|
if (!path || !ref)
|
|
196
|
-
return
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
382
|
+
return "unknown";
|
|
383
|
+
const read = api.get(`contents/${path}?ref=${encodeURIComponent(env.GITHUB_SHA ?? ref)}`).then((f) => Buffer.from(f.content, "base64").toString("utf8"), () => null);
|
|
384
|
+
// A read GitHub never answers mustn't hold the sign-in, and the review after it, up: it can't be told then.
|
|
385
|
+
let timer;
|
|
386
|
+
const late = new Promise((resolve) => {
|
|
387
|
+
timer = setTimeout(() => resolve(null), WORKFLOW_READ_MS);
|
|
388
|
+
});
|
|
389
|
+
const text = await Promise.race([read, late]);
|
|
390
|
+
clearTimeout(timer);
|
|
391
|
+
return claudeInWorkflow(text, input, env.GITHUB_JOB, secret, forCheck);
|
|
392
|
+
}
|
|
393
|
+
/** The same for a ChatGPT login: a workflow that doesn't pass codex-auth-json would never see one saved now. */
|
|
394
|
+
export function chatgptInputMissing(secret = "CODEX_AUTH_JSON") {
|
|
395
|
+
return `The workflow doesn't pass a ChatGPT login to Mergelight, so one connected now would never reach a later run. Add \`codex-auth-json: \${{ secrets.${secret} }}\` under \`with:\` where the workflow uses Mergelight, then push a commit.`;
|
|
200
396
|
}
|
|
201
|
-
|
|
397
|
+
/** What to do when the workflow doesn't pass a Claude login on: a login saved now would never reach a later run. */
|
|
398
|
+
export const CLAUDE_INPUT_MISSING = "The workflow doesn't pass a Claude login to Mergelight, so one connected now would never reach a later run. Add `claude-code-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}` under `with:` where the workflow uses Mergelight, then push a commit.";
|
|
399
|
+
export function githubConnect(api, number, headSha, log, env = process.env, mode = { purpose: "review" }) {
|
|
400
|
+
const checker = mode.purpose === "check" && mode.ai ? mode.ai : null;
|
|
401
|
+
const reviewer = mode.reviewer ?? (checker === "codex" ? "claude" : "codex");
|
|
402
|
+
// Claude's link alone: Claude checks, or Claude must review and has no login yet.
|
|
403
|
+
const onlyClaude = mode.ai === "claude";
|
|
202
404
|
const runUrl = env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : undefined;
|
|
203
405
|
let checkId = null;
|
|
204
406
|
let running = null;
|
|
205
407
|
let claudeOffered = false;
|
|
408
|
+
/** Whether the prompt reached the pull request: only then is there a prompt to replace. */
|
|
409
|
+
let prompted = false;
|
|
410
|
+
/** What tells this run's prompt apart from another run's. */
|
|
411
|
+
let promptMark = "";
|
|
412
|
+
/** Why Claude isn't offered, when the workflow is the reason. */
|
|
413
|
+
let claudeMissing;
|
|
414
|
+
let chatgptMissing;
|
|
206
415
|
/**
|
|
207
416
|
* The app's token dies if the app is removed during the login, which can wait 15 minutes. The comment
|
|
208
417
|
* still has to change, or it keeps offering a dead code, and the workflow's own token can do that.
|
|
209
418
|
*/
|
|
210
|
-
|
|
419
|
+
/** Runs a comment read or write, again with the workflow's token when GitHub refuses the app's. */
|
|
420
|
+
const withWorkflowToken = async (work) => {
|
|
211
421
|
try {
|
|
212
|
-
await
|
|
422
|
+
return await work();
|
|
213
423
|
}
|
|
214
424
|
catch (err) {
|
|
215
425
|
const fallback = env.GITHUB_WORKFLOW_TOKEN;
|
|
@@ -217,23 +427,54 @@ export function githubConnect(api, number, headSha, log, env = process.env) {
|
|
|
217
427
|
throw err;
|
|
218
428
|
log("GitHub refused the app's token, so this updates the comment with the workflow's token.");
|
|
219
429
|
env.GH_TOKEN = fallback;
|
|
220
|
-
await
|
|
430
|
+
return await work();
|
|
221
431
|
}
|
|
222
432
|
};
|
|
433
|
+
const updateSummary = (body) => withWorkflowToken(() => upsertSummary(api, number, body));
|
|
223
434
|
const finish = (title, summary) => writeCheck(api, checkId, headSha, { status: "completed", conclusion: "neutral", completed_at: new Date().toISOString(), output: { title, summary } }, log);
|
|
435
|
+
/**
|
|
436
|
+
* Connected: the check stays going and the review carries it on. A check finished now would stand
|
|
437
|
+
* neutral until the review starts, and a branch rule takes neutral for passed.
|
|
438
|
+
*/
|
|
439
|
+
const handOn = async (title, summary) => {
|
|
440
|
+
if (!checkId)
|
|
441
|
+
return;
|
|
442
|
+
// Outside the Action, no review follows in this run to take the check on. It ends here, cancelled, not
|
|
443
|
+
// neutral: no review ran, so a branch rule must not take it for passed.
|
|
444
|
+
if (!env.MERGELIGHT_PROVIDER) {
|
|
445
|
+
await writeCheck(api, checkId, headSha, { status: "completed", conclusion: "cancelled", completed_at: new Date().toISOString(), output: { title, summary: "No review ran with this. Push a commit, and Mergelight reviews it." } }, log);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
await writeCheck(api, checkId, headSha, { status: "in_progress", output: { title, summary } }, log);
|
|
449
|
+
if (env.GITHUB_ENV)
|
|
450
|
+
appendFileSync(env.GITHUB_ENV, `MERGELIGHT_CHECK_RUN=${checkId}\n`);
|
|
451
|
+
};
|
|
224
452
|
return {
|
|
453
|
+
...(onlyClaude ? { only: "claude" } : {}),
|
|
454
|
+
claudeUnavailable: () => claudeMissing,
|
|
455
|
+
chatgptUnavailable: () => chatgptMissing,
|
|
225
456
|
stopLogin: () => running?.kill("SIGTERM"),
|
|
226
457
|
startClaude: async () => {
|
|
227
|
-
|
|
458
|
+
// Connecting ChatGPT to check a Claude review offers only ChatGPT: Claude already has a login.
|
|
459
|
+
if (checker === "codex")
|
|
460
|
+
return null;
|
|
461
|
+
// Claude is offered only where the workflow passes its login on. Beside ChatGPT, only when that is
|
|
462
|
+
// sure. Asked for by name, also when a reusable workflow may pass it on where this can't see.
|
|
463
|
+
const passes = await workflowHasClaude(api, env, "claude-code-oauth-token", "CLAUDE_CODE_OAUTH_TOKEN", Boolean(checker));
|
|
464
|
+
if (passes === "no") {
|
|
465
|
+
claudeMissing = CLAUDE_INPUT_MISSING;
|
|
466
|
+
return null;
|
|
467
|
+
}
|
|
468
|
+
if (!onlyClaude && passes !== "yes")
|
|
228
469
|
return null;
|
|
229
470
|
const signIn = await startClaudeSignIn();
|
|
230
471
|
if (!signIn) {
|
|
231
|
-
log("Claude's sign-in didn't start, so only ChatGPT is offered.");
|
|
472
|
+
log(onlyClaude ? "Claude's sign-in didn't start." : "Claude's sign-in didn't start, so only ChatGPT is offered.");
|
|
232
473
|
return null;
|
|
233
474
|
}
|
|
234
475
|
const ref = claudeCodeRef(signIn.url);
|
|
235
476
|
if (!ref) {
|
|
236
|
-
log("Claude's sign-in link wasn't the expected shape, so only ChatGPT is offered.");
|
|
477
|
+
log(onlyClaude ? "Claude's sign-in link wasn't the expected shape." : "Claude's sign-in link wasn't the expected shape, so only ChatGPT is offered.");
|
|
237
478
|
signIn.stop();
|
|
238
479
|
return null;
|
|
239
480
|
}
|
|
@@ -246,7 +487,8 @@ export function githubConnect(api, number, headSha, log, env = process.env) {
|
|
|
246
487
|
signIn.stop();
|
|
247
488
|
},
|
|
248
489
|
wait: async () => {
|
|
249
|
-
|
|
490
|
+
// As long as the comment says: a checker's prompt promises the review starts after 15 minutes.
|
|
491
|
+
const code = await waitForPastedCode({ read: () => readCodeRef((path) => api.get(path), ref), stopped: () => over }, checker ? CHECK_WAIT_MS : undefined);
|
|
250
492
|
if (!code)
|
|
251
493
|
return false;
|
|
252
494
|
const token = await signIn.finish(code);
|
|
@@ -254,47 +496,100 @@ export function githubConnect(api, number, headSha, log, env = process.env) {
|
|
|
254
496
|
log("Claude didn't accept that code.");
|
|
255
497
|
return false;
|
|
256
498
|
}
|
|
257
|
-
shareClaudeToken(token, env);
|
|
499
|
+
shareClaudeToken(token, env, console.log, !checker);
|
|
258
500
|
return true;
|
|
259
501
|
},
|
|
260
502
|
};
|
|
261
503
|
},
|
|
262
|
-
startLogin: (onOutput) =>
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
504
|
+
startLogin: async (onOutput) => {
|
|
505
|
+
// Connecting Claude alone starts no ChatGPT sign-in.
|
|
506
|
+
if (onlyClaude)
|
|
507
|
+
return 1;
|
|
508
|
+
// A checker's ChatGPT login is asked for only where the workflow passes it on to later runs.
|
|
509
|
+
if (checker === "codex" && (await workflowHasClaude(api, env, "codex-auth-json", env.SECRET_NAME || "CODEX_AUTH_JSON", true)) === "no") {
|
|
510
|
+
chatgptMissing = chatgptInputMissing(env.SECRET_NAME || "CODEX_AUTH_JSON");
|
|
511
|
+
return 1;
|
|
512
|
+
}
|
|
513
|
+
return new Promise((resolve, reject) => {
|
|
514
|
+
const child = spawn("codex", ["login", "--device-auth"], { stdio: ["ignore", "pipe", "pipe"] });
|
|
515
|
+
running = child;
|
|
516
|
+
// A checker's prompt promises the review starts after 15 minutes.
|
|
517
|
+
const timer = setTimeout(() => child.kill("SIGTERM"), checker ? CHECK_WAIT_MS : LOGIN_TIMEOUT_MS);
|
|
518
|
+
child.stdout.setEncoding("utf8").on("data", onOutput);
|
|
519
|
+
child.stderr.setEncoding("utf8").on("data", onOutput);
|
|
520
|
+
child.on("error", (err) => {
|
|
521
|
+
clearTimeout(timer);
|
|
522
|
+
reject(err);
|
|
523
|
+
});
|
|
524
|
+
child.on("close", (code) => {
|
|
525
|
+
clearTimeout(timer);
|
|
526
|
+
resolve(code ?? 1);
|
|
527
|
+
});
|
|
275
528
|
});
|
|
276
|
-
}
|
|
529
|
+
},
|
|
277
530
|
showCode: async (login, claudeUrl) => {
|
|
278
|
-
|
|
531
|
+
const setupLink = claudeSetupLink(env.GITHUB_REPOSITORY, number);
|
|
532
|
+
prompted = true;
|
|
533
|
+
// What tells this run's prompt apart from any other: its code, or its Claude link as the hidden line
|
|
534
|
+
// keeps it, with "--" escaped. The review that starts after it replaces this one, and no other.
|
|
535
|
+
const mark = login?.code ?? (claudeUrl ? JSON.stringify(claudeUrl).slice(1, -1).replace(/--/g, "\\u002d\\u002d") : "");
|
|
536
|
+
promptMark = mark;
|
|
537
|
+
if (mark && env.GITHUB_ENV)
|
|
538
|
+
appendFileSync(env.GITHUB_ENV, `MERGELIGHT_PROMPT=${mark}\n`);
|
|
539
|
+
// What tells this run's prompt apart from any other: its code, or its Claude link.
|
|
540
|
+
await upsertSummary(api, number, checker ? connectCheckBody(checker, reviewer, login, runUrl, claudeUrl, setupLink) : connectBody(login, runUrl, claudeUrl, setupLink));
|
|
279
541
|
log("Posted the link and code on the pull request. Waiting for the login.");
|
|
280
542
|
// The comment is what people need. A check that can't be written shouldn't end a login that can still work.
|
|
281
543
|
try {
|
|
282
544
|
const run = await writeCheck(api, null, headSha, {
|
|
283
545
|
status: "in_progress",
|
|
284
546
|
started_at: new Date().toISOString(),
|
|
285
|
-
output:
|
|
547
|
+
output: checker
|
|
548
|
+
? { title: checkWaitingTitle(checker), summary: `Follow the steps in the pull request's Mergelight comment. Without it, the review starts in 15 minutes, checked by ${aiName(reviewer)}.` }
|
|
549
|
+
: { title: onlyClaude ? "Waiting for you to connect Claude" : claudeUrl ? "Waiting for you to connect your AI" : "Waiting for you to connect ChatGPT", summary: "Follow the steps in the pull request's Mergelight comment." },
|
|
286
550
|
}, log);
|
|
287
551
|
checkId = run?.id ?? null;
|
|
552
|
+
// Known from now on: if the run is cancelled while it waits, its last step finishes this check.
|
|
553
|
+
if (checkId && env.GITHUB_ENV)
|
|
554
|
+
appendFileSync(env.GITHUB_ENV, `MERGELIGHT_CHECK_RUN=${checkId}\n`);
|
|
288
555
|
}
|
|
289
556
|
catch (err) {
|
|
290
557
|
log(`Couldn't show the waiting check: ${err instanceof Error ? err.message : String(err)}`);
|
|
291
558
|
}
|
|
292
559
|
},
|
|
293
560
|
connected: async (via = "chatgpt") => {
|
|
294
|
-
|
|
561
|
+
// Only while the summary is still this run's prompt: another run may have posted its own since. A
|
|
562
|
+
// comment that can't be updated mustn't leave the check waiting.
|
|
563
|
+
const { summary } = await withWorkflowToken(() => readPrReviewState(api, number)).catch(() => ({ summary: undefined }));
|
|
564
|
+
if (!promptMark || summary?.body?.includes(promptMark))
|
|
565
|
+
await updateSummary(pendingSummaryBody()).catch((err) => log(`Couldn't update the comment: ${err instanceof Error ? err.message : String(err)}`));
|
|
566
|
+
if (checker) {
|
|
567
|
+
let account = null;
|
|
568
|
+
if (checker === "codex") {
|
|
569
|
+
try {
|
|
570
|
+
account = connectedAccount(readFileSync(join(env.CODEX_HOME ?? "", "auth.json"), "utf8"));
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
// Without the file the note just doesn't name the account.
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
// A ChatGPT login now, as one from the secret would be: a rejected one is then known as such, so
|
|
577
|
+
// the reviewer can check instead, and the steps that refresh and save it run.
|
|
578
|
+
if (checker === "codex" && env.GITHUB_ENV)
|
|
579
|
+
appendFileSync(env.GITHUB_ENV, "MERGELIGHT_CHATGPT=1\n");
|
|
580
|
+
const who = checker === "claude" ? "the Claude plan that confirmed the sign-in" : account ? `the ChatGPT account \`${account}\`` : "the ChatGPT account that entered the code";
|
|
581
|
+
const secret = checker === "claude" ? "CLAUDE_CODE_OAUTH_TOKEN" : env.SECRET_NAME || "CODEX_AUTH_JSON";
|
|
582
|
+
// The note failing to post mustn't leave the check waiting.
|
|
583
|
+
await api
|
|
584
|
+
.write("POST", `issues/${number}/comments`, { body: `🔌 ${aiName(checker)} now checks reviews on this repository, with ${who}. If that isn't yours, remove the \`${secret}\` secret and push a commit to connect again.` })
|
|
585
|
+
.catch((err) => log(`Couldn't post who connected: ${err instanceof Error ? err.message : String(err)}`));
|
|
586
|
+
await handOn(`Connected to ${loginName(checker)}`, `Starting the review, checked by ${aiName(checker)}.`);
|
|
587
|
+
log(`Connected to ${loginName(checker)} to check the review.`);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
295
590
|
if (via === "claude") {
|
|
296
591
|
await api.write("POST", `issues/${number}/comments`, { body: "🔌 Reviews on this repository now use the Claude plan that confirmed the sign-in. If that isn't yours, remove the `CLAUDE_CODE_OAUTH_TOKEN` secret and push a commit to connect again." });
|
|
297
|
-
await
|
|
592
|
+
await handOn("Connected to Claude", "Starting the review.");
|
|
298
593
|
log("Connected to Claude.");
|
|
299
594
|
return;
|
|
300
595
|
}
|
|
@@ -305,14 +600,32 @@ export function githubConnect(api, number, headSha, log, env = process.env) {
|
|
|
305
600
|
catch {
|
|
306
601
|
// Without the file the note just doesn't name the account.
|
|
307
602
|
}
|
|
603
|
+
// A ChatGPT login now, as one from the secret would be, so a rejected one is called that.
|
|
604
|
+
if (env.GITHUB_ENV)
|
|
605
|
+
appendFileSync(env.GITHUB_ENV, "MERGELIGHT_CHATGPT=1\n");
|
|
308
606
|
await api.write("POST", `issues/${number}/comments`, { body: connectedBody(connectedAccount(auth), env.SECRET_NAME || "CODEX_AUTH_JSON") });
|
|
309
|
-
await
|
|
607
|
+
await handOn("Connected to ChatGPT", "Starting the review.");
|
|
310
608
|
log("Connected to ChatGPT.");
|
|
311
609
|
},
|
|
312
610
|
failed: async (reason) => {
|
|
611
|
+
// A checker that wasn't connected holds nothing up: the review starts, checked by the reviewer's AI,
|
|
612
|
+
// and its summary says so. The comment it replaces is the connect one, so it is left for the review.
|
|
613
|
+
if (checker) {
|
|
614
|
+
// The prompt stays until the review that starts now replaces it: changing the comment here could
|
|
615
|
+
// overwrite a newer run's finished review, as reading it first doesn't stop that.
|
|
616
|
+
// The review goes on, so the check does too: it isn't finished in between.
|
|
617
|
+
await handOn(`${loginName(checker)} wasn't connected`, `${reason} The review goes on, checked by ${aiName(reviewer)}.`).catch((err) => log(`Couldn't update the check: ${err instanceof Error ? err.message : String(err)}`));
|
|
618
|
+
log(`${reason} The review goes on, checked by ${aiName(reviewer)}.`);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
313
621
|
// One failed write mustn't stop the other. Only the app that made a check can finish it.
|
|
314
|
-
await updateSummary(connectFailedBody(reason, claudeOffered)).catch((err) => log(`Couldn't update the comment: ${err instanceof Error ? err.message : String(err)}`));
|
|
315
|
-
await finish(CHECK_FAILED_TITLE, reason).
|
|
622
|
+
await updateSummary(connectFailedBody(reason, claudeOffered, onlyClaude)).catch((err) => log(`Couldn't update the comment: ${err instanceof Error ? err.message : String(err)}`));
|
|
623
|
+
const finished = await finish(CHECK_FAILED_TITLE, reason).then(() => true, (err) => (log(`Couldn't finish the check: ${err instanceof Error ? err.message : String(err)}`), false));
|
|
624
|
+
// Finished here: nothing is left for the run's last step to finish. Not finished: it still is.
|
|
625
|
+
if (finished && env.GITHUB_ENV)
|
|
626
|
+
appendFileSync(env.GITHUB_ENV, "MERGELIGHT_CHECK_RUN=\n");
|
|
627
|
+
// No review runs, as when one fails.
|
|
628
|
+
await takeBackOlderApprovals(api, number, headSha, log);
|
|
316
629
|
log(reason);
|
|
317
630
|
},
|
|
318
631
|
};
|
package/dist/github.js
CHANGED
|
@@ -58,6 +58,11 @@ export async function fetchPullRequest(ref) {
|
|
|
58
58
|
baseRef: pull.base.ref,
|
|
59
59
|
baseSha: pull.base.sha,
|
|
60
60
|
headSha: pull.head.sha,
|
|
61
|
+
headRef: pull.head.ref,
|
|
62
|
+
headRepo: pull.head.repo?.full_name ?? null,
|
|
63
|
+
state: pull.state,
|
|
64
|
+
defaultBranch: pull.base.repo?.default_branch,
|
|
65
|
+
sameRepo: pull.head.repo?.id !== undefined && pull.head.repo.id === pull.base.repo?.id,
|
|
61
66
|
additions: pull.additions,
|
|
62
67
|
deletions: pull.deletions,
|
|
63
68
|
changedFiles: pull.changed_files,
|