@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.
Files changed (43) hide show
  1. package/LICENSE.md +110 -0
  2. package/README.md +113 -2
  3. package/dist/action-source.js +107 -0
  4. package/dist/checks.js +108 -0
  5. package/dist/cli.js +296 -0
  6. package/dist/cloud.js +330 -0
  7. package/dist/connect-claude.js +157 -0
  8. package/dist/connect.js +319 -0
  9. package/dist/github.js +65 -0
  10. package/dist/init.js +92 -0
  11. package/dist/mcp/findings.js +252 -0
  12. package/dist/mcp/server.js +168 -0
  13. package/dist/prompt.js +503 -0
  14. package/dist/providers/claude.js +102 -0
  15. package/dist/providers/codex.js +251 -0
  16. package/dist/providers/index.js +8 -0
  17. package/dist/publish/api.js +63 -0
  18. package/dist/publish/closed.js +88 -0
  19. package/dist/publish/diff-lines.js +50 -0
  20. package/dist/publish/handled.js +98 -0
  21. package/dist/publish/markdown.js +233 -0
  22. package/dist/publish/publish.js +397 -0
  23. package/dist/publish/state.js +82 -0
  24. package/dist/publish/team-checks.js +72 -0
  25. package/dist/render.js +129 -0
  26. package/dist/review.js +366 -0
  27. package/dist/run.js +57 -0
  28. package/dist/schema.js +155 -0
  29. package/dist/setup.js +180 -0
  30. package/dist/skills.js +127 -0
  31. package/dist/types.js +1 -0
  32. package/dist/update.js +36 -0
  33. package/dist/workspace.js +318 -0
  34. package/package.json +36 -4
  35. package/scripts/app-token.mjs +69 -0
  36. package/scripts/mask-login.mjs +26 -0
  37. package/scripts/refresh-login.mjs +171 -0
  38. package/scripts/save-claude-login.sh +22 -0
  39. package/scripts/save-login.sh +30 -0
  40. package/skills/mergelight/SKILL.md +66 -0
  41. package/templates/mergelight-approve.yml +21 -0
  42. package/templates/mergelight-refresh.yml +23 -0
  43. package/templates/mergelight.yml +42 -0
@@ -0,0 +1,318 @@
1
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs";
2
+ import { homedir, tmpdir } from "node:os";
3
+ import { join, posix } from "node:path";
4
+ import { run, runOk } from "./run.js";
5
+ import { importSkills, SKILL_GIT_TIMEOUT_MS, SKILL_IMPORT_TIMEOUT_MS } from "./skills.js";
6
+ /** Lockfiles and generated files are left out of the diff the model sees. */
7
+ const EXCLUDES = [
8
+ "package-lock.json",
9
+ "yarn.lock",
10
+ "pnpm-lock.yaml",
11
+ "bun.lock",
12
+ "bun.lockb",
13
+ "Cargo.lock",
14
+ "poetry.lock",
15
+ "Gemfile.lock",
16
+ "go.sum",
17
+ "*.snap",
18
+ "*.min.js",
19
+ "*.map",
20
+ ".snapshot-*.json",
21
+ ].map((p) => `:(glob,exclude)**/${p}`).concat([
22
+ ":(glob,exclude)**/__snapshots__/**",
23
+ ":(glob,exclude)**/dist/**",
24
+ ]);
25
+ /** Above this size the diff is not inlined and the model reads it file by file. */
26
+ const MAX_INLINE_DIFF = 400_000;
27
+ export function cacheDir() {
28
+ return process.env.MERGELIGHT_CACHE ?? join(homedir(), ".cache", "mergelight");
29
+ }
30
+ /** git, authenticated through gh for this call only, never prompting. */
31
+ function git(args, cwd) {
32
+ return runOk("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", ...args], { cwd, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
33
+ }
34
+ /**
35
+ * Mergelight's own folder in the checkout, for the files it writes there: a diff too large for the
36
+ * prompt, and the team's skills. The checkout holds the pull request's files, so the pull request
37
+ * could have put a link at one of those names, to make a write land somewhere else on the machine.
38
+ * A link or a file in the way is removed, never written through.
39
+ */
40
+ export function ownFolder(checkout) {
41
+ const dir = join(checkout, ".mergelight");
42
+ if (lstatSync(dir, { throwIfNoEntry: false })?.isDirectory() === false)
43
+ rmSync(dir, { force: true });
44
+ mkdirSync(dir, { recursive: true });
45
+ // Removing a link removes the link alone, not what it points at.
46
+ for (const name of ["pr.diff", "skills"])
47
+ rmSync(join(dir, name), { recursive: true, force: true });
48
+ return dir;
49
+ }
50
+ /**
51
+ * Skill folders Codex finds by itself and offers to the model. In the checkout they are the pull
52
+ * request's, so its author could plant one that tells the reviewers what to skip. Codex has a switch
53
+ * to stop that, but not every version has it, so the folders go. The diff still shows them.
54
+ */
55
+ export const AGENT_SKILL_FOLDERS = [".agents/skills", ".codex/skills"];
56
+ export function removeAgentSkills(checkout) {
57
+ for (const folder of AGENT_SKILL_FOLDERS) {
58
+ const parent = join(checkout, folder.split("/")[0]);
59
+ const kind = lstatSync(parent, { throwIfNoEntry: false });
60
+ if (!kind)
61
+ continue;
62
+ // .codex or .agents can be a link the pull request made, to a folder anywhere on the machine.
63
+ // Going through it would delete that folder's skills. A link or a file goes, alone.
64
+ if (!kind.isDirectory()) {
65
+ rmSync(parent, { force: true });
66
+ continue;
67
+ }
68
+ // rmSync removes a link at this name without following it.
69
+ rmSync(join(parent, "skills"), { recursive: true, force: true });
70
+ }
71
+ }
72
+ /**
73
+ * Copies the team's skills, and never lets that stop or hold up a review. The mirror has no file
74
+ * contents of its own, so reading a skill the pull request changed asks GitHub for it: with the
75
+ * same login as every other git call here, never with a prompt, and never for long.
76
+ */
77
+ async function skillsFor(mirror, base, checkout, folders) {
78
+ if (!folders.length)
79
+ return [];
80
+ const gitInMirror = (args) => run("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "-C", mirror, ...args], {
81
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
82
+ timeoutMs: SKILL_GIT_TIMEOUT_MS,
83
+ });
84
+ let timer;
85
+ // A last stop, for a git process that doesn't end even when told to.
86
+ const gaveUp = new Promise((resolve) => {
87
+ timer = setTimeout(() => resolve([]), SKILL_IMPORT_TIMEOUT_MS + 2 * SKILL_GIT_TIMEOUT_MS);
88
+ timer.unref();
89
+ });
90
+ try {
91
+ return await Promise.race([importSkills(mirror, base, checkout, folders, gitInMirror).catch(() => []), gaveUp]);
92
+ }
93
+ finally {
94
+ clearTimeout(timer);
95
+ }
96
+ }
97
+ /** The root instruction files whose conventions the reviewers follow, read from the base branch. */
98
+ export const CONVENTION_FILES = ["AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md", ".github/CONTRIBUTING.md", "docs/CONTRIBUTING.md", ".github/copilot-instructions.md"];
99
+ /** Per file, so one long file can't fill every prompt. */
100
+ export const MAX_CONVENTION_CHARS = 12_000;
101
+ /** All files together, and how many. */
102
+ export const MAX_CONVENTIONS_CHARS = 40_000;
103
+ export const MAX_CONVENTION_FILES = 12;
104
+ /** A file larger than this isn't read at all. */
105
+ const MAX_CONVENTION_BYTES = 256_000;
106
+ /** Which instruction files apply: the root ones, AGENTS.md or CLAUDE.md in a folder above a changed file, and .github/instructions. */
107
+ export function conventionPaths(all, changedPaths) {
108
+ const folders = new Set();
109
+ for (const changed of changedPaths) {
110
+ const parts = changed.split("/").slice(0, -1);
111
+ for (let i = 1; i <= parts.length; i++)
112
+ folders.add(parts.slice(0, i).join("/"));
113
+ }
114
+ const present = new Set(all);
115
+ const root = CONVENTION_FILES.filter((p) => present.has(p));
116
+ const github = all.filter((p) => p.startsWith(".github/instructions/") && p.endsWith(".instructions.md")).sort();
117
+ const nested = all
118
+ .filter((p) => {
119
+ const at = p.lastIndexOf("/");
120
+ return at > 0 && ["AGENTS.md", "CLAUDE.md"].includes(p.slice(at + 1)) && folders.has(p.slice(0, at));
121
+ })
122
+ // Closest to the root first: a folder's file comes before the ones in its subfolders.
123
+ .sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
124
+ // The rules closest to the changed code come before .github/instructions, so they aren't the ones crowded out.
125
+ return [...root, ...nested, ...github];
126
+ }
127
+ /**
128
+ * The team's instruction files as the base branch has them. The checkout is the pull request's, and
129
+ * its author could add or rewrite AGENTS.md there to steer the reviewers. A file that is a link is
130
+ * followed once, to a file inside the repository. A file that is missing, too large, or can't be
131
+ * read in time is left out: it never stops a review.
132
+ */
133
+ export async function conventionsFor(mirror, base, changedPaths = []) {
134
+ const git = (args) => run("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "-C", mirror, ...args], {
135
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
136
+ timeoutMs: SKILL_GIT_TIMEOUT_MS,
137
+ }).catch(() => null);
138
+ const listed = await git(["ls-tree", "-r", "-z", "--full-tree", base]);
139
+ if (listed?.code !== 0)
140
+ return [];
141
+ const tree = new Map();
142
+ for (const entry of listed.stdout.split("\0")) {
143
+ const m = /^(\d{6}) blob ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(entry);
144
+ if (m)
145
+ tree.set(m[3], { mode: m[1], sha: m[2] });
146
+ }
147
+ const blob = async (sha) => {
148
+ const sized = await git(["cat-file", "-s", sha]);
149
+ if (sized?.code !== 0 || !(Number(sized.stdout.trim()) <= MAX_CONVENTION_BYTES))
150
+ return null;
151
+ const read = await git(["cat-file", "blob", sha]);
152
+ return read?.code === 0 ? read.stdout : null;
153
+ };
154
+ const read = async (path) => {
155
+ let file = tree.get(path);
156
+ if (file?.mode === "120000") {
157
+ // A link: git keeps the target's path as its content.
158
+ const target = (await blob(file.sha))?.trim() ?? "";
159
+ const resolved = posix.normalize(posix.join(posix.dirname(path), target));
160
+ if (!target || target.startsWith("/") || resolved === ".." || resolved.startsWith("../"))
161
+ return null;
162
+ file = tree.get(resolved);
163
+ }
164
+ if (!file || (file.mode !== "100644" && file.mode !== "100755"))
165
+ return null;
166
+ const text = (await blob(file.sha))?.trim();
167
+ return text ? { path, sha: file.sha, text } : null;
168
+ };
169
+ const found = await Promise.all(conventionPaths([...tree.keys()], changedPaths).slice(0, MAX_CONVENTION_FILES * 2).map(read));
170
+ const conventions = [];
171
+ const seen = new Set();
172
+ let total = 0;
173
+ for (const f of found) {
174
+ // AGENTS.md and CLAUDE.md are often one file and a link to it: the text goes in once.
175
+ if (!f || seen.has(f.sha) || conventions.length >= MAX_CONVENTION_FILES)
176
+ continue;
177
+ const room = Math.min(MAX_CONVENTION_CHARS, MAX_CONVENTIONS_CHARS - total);
178
+ if (room <= 0)
179
+ break;
180
+ seen.add(f.sha);
181
+ conventions.push({ path: f.path, text: f.text.slice(0, room), truncated: f.text.length > room });
182
+ total += Math.min(f.text.length, room);
183
+ }
184
+ return conventions;
185
+ }
186
+ /** The answer, or the fallback once the time is up, for work that must never hold up a review. */
187
+ async function withDeadline(work, ms, fallback) {
188
+ let timer;
189
+ const gaveUp = new Promise((resolve) => {
190
+ timer = setTimeout(() => resolve(fallback), ms);
191
+ timer.unref();
192
+ });
193
+ try {
194
+ return await Promise.race([work.catch(() => fallback), gaveUp]);
195
+ }
196
+ finally {
197
+ clearTimeout(timer);
198
+ }
199
+ }
200
+ async function hasCommit(mirror, sha) {
201
+ const r = await run("git", ["-C", mirror, "cat-file", "-e", `${sha}^{commit}`]);
202
+ return r.code === 0;
203
+ }
204
+ /** Serializes work on one mirror across processes, so parallel reviews don't trip over each other. */
205
+ async function withLock(dir, fn) {
206
+ const lock = join(dir, "mergelight.lock");
207
+ const started = Date.now();
208
+ for (;;) {
209
+ try {
210
+ mkdirSync(lock);
211
+ break;
212
+ }
213
+ catch {
214
+ try {
215
+ if (Date.now() - statSync(lock).mtimeMs > 10 * 60_000)
216
+ rmSync(lock, { recursive: true, force: true });
217
+ }
218
+ catch {
219
+ /* the lock went away between calls */
220
+ }
221
+ if (Date.now() - started > 15 * 60_000)
222
+ throw new Error(`Timed out waiting for ${lock}`);
223
+ await new Promise((r) => setTimeout(r, 500));
224
+ }
225
+ }
226
+ try {
227
+ return await fn();
228
+ }
229
+ finally {
230
+ rmSync(lock, { recursive: true, force: true });
231
+ }
232
+ }
233
+ /**
234
+ * Keeps a blobless bare mirror of the repository in the cache, fetches the PR,
235
+ * and checks out the commit under review in a temporary worktree.
236
+ */
237
+ export async function prepareWorkspace(pr, at, skillFolders = []) {
238
+ const mirror = join(cacheDir(), "repos", pr.owner, `${pr.repo}.git`);
239
+ mkdirSync(join(cacheDir(), "repos", pr.owner), { recursive: true });
240
+ if (!existsSync(mirror)) {
241
+ await git(["clone", "--bare", "--filter=blob:none", "--quiet", `https://github.com/${pr.owner}/${pr.repo}.git`, mirror]);
242
+ }
243
+ return withLock(mirror, async () => {
244
+ const fetch = (...refspecs) => git(["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "origin", ...refspecs], mirror);
245
+ await fetch(`+refs/pull/${pr.number}/head:refs/mergelight/pull/${pr.number}`);
246
+ // The base branch may be gone (deleted after merge). Its recorded commit is enough then.
247
+ let haveBaseBranch = true;
248
+ try {
249
+ await fetch(`+refs/heads/${pr.baseRef}:refs/mergelight/base/${pr.baseRef}`);
250
+ }
251
+ catch {
252
+ haveBaseBranch = false;
253
+ }
254
+ const headSha = at ?? pr.headSha;
255
+ for (const sha of [headSha, pr.baseSha]) {
256
+ if (!(await hasCommit(mirror, sha))) {
257
+ try {
258
+ await fetch(sha);
259
+ }
260
+ catch (err) {
261
+ if (sha === headSha)
262
+ throw err;
263
+ }
264
+ }
265
+ }
266
+ const baseCandidate = (await hasCommit(mirror, pr.baseSha))
267
+ ? pr.baseSha
268
+ : haveBaseBranch
269
+ ? `refs/mergelight/base/${pr.baseRef}`
270
+ : null;
271
+ if (!baseCandidate) {
272
+ throw new Error(`Can't find the base of #${pr.number}: branch ${pr.baseRef} is gone and commit ${pr.baseSha.slice(0, 7)} isn't fetchable.`);
273
+ }
274
+ const mergeBase = (await git(["merge-base", baseCandidate, headSha], mirror)).stdout.trim();
275
+ const range = `${mergeBase}...${headSha}`;
276
+ const diffArgs = ["--no-color", "--no-ext-diff", "--find-renames", range, "--", ...EXCLUDES];
277
+ const diff = (await git(["diff", "-U5", ...diffArgs], mirror)).stdout;
278
+ const diffStat = (await git(["diff", "--stat=200,150", ...diffArgs], mirror)).stdout.trim();
279
+ const changedFiles = (await git(["diff", "--numstat", "--no-renames", ...diffArgs.filter((a) => a !== "--find-renames")], mirror)).stdout
280
+ .trim()
281
+ .split("\n")
282
+ .filter(Boolean)
283
+ .map((line) => {
284
+ const [added, removed, path] = line.split("\t");
285
+ return { path: path ?? "", added: Number(added) || 0, removed: Number(removed) || 0 };
286
+ });
287
+ // -z gives each path as it is, ended by a NUL. Without it git puts quotes around a name with odd characters in it.
288
+ const touchedPaths = (await git(["diff", "--name-only", "-z", "--no-renames", "--no-color", "--no-ext-diff", range], mirror)).stdout.split("\0").filter(Boolean);
289
+ const dir = mkdtempSync(join(tmpdir(), `mergelight-${pr.repo}-${pr.number}-`));
290
+ await git(["worktree", "add", "--quiet", "--detach", dir, headSha], mirror);
291
+ ownFolder(dir);
292
+ removeAgentSkills(dir);
293
+ // From the base branch as it is now: what the team merged. Not from the pull request, and not from
294
+ // the commit it branched from either. Its author picks that commit, and could pick one from
295
+ // before a skill was written or tightened.
296
+ // The same goes for the instruction files.
297
+ const teamBase = haveBaseBranch ? `refs/mergelight/base/${pr.baseRef}` : baseCandidate;
298
+ const skills = await skillsFor(mirror, teamBase, dir, skillFolders);
299
+ const conventions = await withDeadline(conventionsFor(mirror, teamBase, touchedPaths), SKILL_IMPORT_TIMEOUT_MS + 2 * SKILL_GIT_TIMEOUT_MS, []);
300
+ return {
301
+ dir,
302
+ mergeBase,
303
+ headSha,
304
+ diff,
305
+ diffStat,
306
+ diffTruncated: diff.length > MAX_INLINE_DIFF,
307
+ changedFiles,
308
+ touchedPaths,
309
+ skills,
310
+ conventions,
311
+ cleanup: async () => {
312
+ await run("git", ["-C", mirror, "worktree", "remove", "--force", dir]);
313
+ rmSync(dir, { recursive: true, force: true });
314
+ await run("git", ["-C", mirror, "worktree", "prune"]);
315
+ },
316
+ };
317
+ });
318
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@mergelight/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.15",
4
+ "description": "AI code review that runs on the Claude or ChatGPT plan you already pay for.",
5
+ "type": "module",
6
+ "bin": {
7
+ "mergelight": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "scripts",
12
+ "skills",
13
+ "templates"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsc -p .",
17
+ "prepack": "npm run build",
18
+ "dev": "tsc -p . --watch",
19
+ "test": "tsc -p . && node --test test/*.test.mjs"
20
+ },
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "homepage": "https://mergelight.dev",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/mergelightai/mergelight.git",
28
+ "directory": "packages/mergelight"
29
+ },
30
+ "license": "FSL-1.1-MIT",
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.20.5",
36
+ "typescript": "^7.0.2"
37
+ }
38
+ }
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+ // Lets a run post as the Mergelight AI app: swaps GitHub's OIDC token for a short-lived app token.
3
+ //
4
+ // Whatever goes wrong here, it must not stop the review. The Action then posts with the workflow's
5
+ // own token, as github-actions[bot], and this prints why.
6
+
7
+ import { appendFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const AUDIENCE = "mergelight";
11
+ const SETUP_HINT = "Posting as github-actions[bot].";
12
+
13
+ // A sleeping server can take about a minute to wake up, so the timeout is generous.
14
+ async function fetchWithRetry(fetchImpl, url, init, wait, attempts = 3) {
15
+ for (let attempt = 1; ; attempt++) {
16
+ try {
17
+ const res = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(90_000) });
18
+ if (res.status < 500 || attempt === attempts) return res;
19
+ } catch (err) {
20
+ if (attempt === attempts) throw err;
21
+ }
22
+ await wait(1000 * attempt);
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Returns the app token, or null with the reason already printed.
28
+ * log gets the workflow commands, so they reach the run's log and annotations.
29
+ */
30
+ export async function getAppToken({ env = process.env, fetchImpl = fetch, log = console.log, wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
31
+ if (!env.TOKEN_SERVER) return null;
32
+ const scope = env.TOKEN_SCOPE;
33
+ const server = new URL(env.TOKEN_SERVER);
34
+ if (scope) server.searchParams.set("scope", scope);
35
+ const fallback = scope ? "" : ` ${SETUP_HINT}`;
36
+ if (!env.ACTIONS_ID_TOKEN_REQUEST_URL || !env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) {
37
+ log(`::notice::Add "id-token: write" to the workflow's permissions to use the Mergelight AI app.${fallback}`);
38
+ return null;
39
+ }
40
+
41
+ try {
42
+ const url = new URL(env.ACTIONS_ID_TOKEN_REQUEST_URL);
43
+ url.searchParams.set("audience", AUDIENCE);
44
+ const oidc = await fetchWithRetry(fetchImpl, url, { headers: { authorization: `Bearer ${env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` } }, wait);
45
+ if (!oidc.ok) throw new Error(`GitHub answered ${oidc.status} for the OIDC token`);
46
+ const { value } = await oidc.json();
47
+ log(`::add-mask::${value}`);
48
+
49
+ const res = await fetchWithRetry(fetchImpl, server, { method: "POST", headers: { authorization: `Bearer ${value}` } }, wait);
50
+ const body = await res.json().catch(() => ({}));
51
+ if (res.ok && body.token) {
52
+ log(`::add-mask::${body.token}`);
53
+ if (!scope) log(`Posting as Mergelight AI, with a token for ${body.repository}.`);
54
+ return body.token;
55
+ }
56
+ // Not installed is a normal choice, not a problem.
57
+ const level = body.error === "not_installed" ? "notice" : "warning";
58
+ log(`::${level}::${body.message ?? `The token server answered ${res.status}.`}${fallback}`);
59
+ return null;
60
+ } catch (err) {
61
+ log(`::warning::Couldn't reach the token server (${err instanceof Error ? err.message : "unknown error"}).${fallback}`);
62
+ return null;
63
+ }
64
+ }
65
+
66
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
67
+ const token = await getAppToken();
68
+ if (token && process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `token=${token}\n`);
69
+ }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // Tells GitHub to hide the Codex login's tokens in this job's logs. GitHub hides a secret as a whole,
3
+ // but not the tokens inside it, and refreshed tokens aren't secrets it knows about at all.
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const TOKENS = ["access_token", "refresh_token", "id_token"];
10
+
11
+ /** Prints a hide command for each token in the login file. A missing or broken file has nothing to hide. */
12
+ export function maskLogin({ env = process.env, log = console.log } = {}) {
13
+ let tokens;
14
+ try {
15
+ tokens = JSON.parse(readFileSync(join(env.CODEX_HOME, "auth.json"), "utf8")).tokens;
16
+ } catch {
17
+ return;
18
+ }
19
+ for (const name of TOKENS) {
20
+ const value = tokens?.[name];
21
+ // A line break would end the command, and the rest would be read as a new one.
22
+ if (typeof value === "string" && value && !/[\r\n]/.test(value)) log(`::add-mask::${value}`);
23
+ }
24
+ }
25
+
26
+ if (process.argv[1] === fileURLToPath(import.meta.url)) maskLogin();
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+ // Refreshes the Codex login before Codex would, and saves it straight away.
3
+ //
4
+ // A used refresh token keeps working for a while, then gets refused: it still worked 18 minutes after
5
+ // its first use and was refused by 38, in one test. A run only has the login that was saved when it
6
+ // started. Codex itself refreshes in a token's last 5 minutes and we only save at the end of the run, so
7
+ // a long review could leave others holding a token about to be refused. Refreshing here keeps tokens
8
+ // away from those 5 minutes and shrinks the gap between refreshing and saving from minutes to seconds.
9
+ //
10
+ // An access token lasts 10 days and keeps working after a refresh, so a run that loses the race can
11
+ // carry on with the one it has, and a refresh doesn't disturb the reviews already running.
12
+
13
+ import { spawn, spawnSync } from "node:child_process";
14
+ import { appendFileSync, readFileSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { getAppToken } from "./app-token.mjs";
18
+ import { maskLogin } from "./mask-login.mjs";
19
+
20
+ const HOUR = 3_600_000;
21
+ /** Longer than a review's 45 minute job limit, so Codex won't need to refresh during one. */
22
+ const REVIEW_WITHIN = HOUR;
23
+ /**
24
+ * A review that lost the race needs its token to outlast it, because Codex would try the used refresh
25
+ * token in the token's last 5 minutes. Most reviews finish well inside this.
26
+ */
27
+ const CARRY_ON_ABOVE = 20 * 60_000;
28
+
29
+ /** When the login's access token expires, in milliseconds, or null if that can't be told. */
30
+ export function accessTokenExpiry(auth) {
31
+ try {
32
+ const { exp } = JSON.parse(Buffer.from(auth.tokens.access_token.split(".")[1], "base64url").toString());
33
+ return typeof exp === "number" ? exp * 1000 : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Whether this run should refresh. The job always does: it also shows a login has stopped working
41
+ * within days, not at the next review. A review only does when its token could run out during it.
42
+ */
43
+ export function isDue(event, expiry, now) {
44
+ if (event === "schedule" || event === "workflow_dispatch") return true;
45
+ return expiry !== null && expiry - now < REVIEW_WITHIN;
46
+ }
47
+
48
+ /**
49
+ * Asks Codex's app-server to refresh, which is the one way to force it without calling OpenAI's
50
+ * token endpoint ourselves. A failed refresh still answers normally, so the caller compares tokens.
51
+ * Returns the reason if it can tell that something went wrong. Its logs stay out of ours, since they
52
+ * deal with the login.
53
+ */
54
+ export function forceRefresh({ env = process.env, spawnImpl = spawn, timeoutMs = 90_000 } = {}) {
55
+ return new Promise((resolve) => {
56
+ const child = spawnImpl("codex", ["app-server"], { stdio: ["pipe", "pipe", "ignore"], env });
57
+ const send = (message) => child.stdin.write(`${JSON.stringify(message)}\n`);
58
+ let done = false;
59
+ const finish = (reason = null) => {
60
+ if (done) return;
61
+ done = true;
62
+ clearTimeout(timer);
63
+ child.kill();
64
+ resolve(reason);
65
+ };
66
+ const timer = setTimeout(() => finish("Codex didn't answer in time"), timeoutMs);
67
+ child.on("error", (err) => finish(err.message));
68
+ child.on("close", () => finish());
69
+ child.stdin.on("error", (err) => finish(err.message));
70
+ let buffer = "";
71
+ child.stdout.on("data", (chunk) => {
72
+ buffer += chunk;
73
+ let nl;
74
+ while ((nl = buffer.indexOf("\n")) >= 0) {
75
+ const line = buffer.slice(0, nl);
76
+ buffer = buffer.slice(nl + 1);
77
+ let message;
78
+ try {
79
+ message = JSON.parse(line);
80
+ } catch {
81
+ continue;
82
+ }
83
+ if (message.error && (message.id === 1 || message.id === 2)) {
84
+ finish(String(message.error.message).slice(0, 200));
85
+ } else if (message.id === 1) {
86
+ send({ method: "initialized" });
87
+ send({ id: 2, method: "account/read", params: { refreshToken: true } });
88
+ } else if (message.id === 2) {
89
+ finish();
90
+ }
91
+ }
92
+ });
93
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "mergelight", title: null, version: "0" }, capabilities: null } });
94
+ });
95
+ }
96
+
97
+ const left = (ms) => (ms >= 2 * 24 * HOUR ? `${Math.floor(ms / (24 * HOUR))} days` : ms >= 2 * HOUR ? `${Math.floor(ms / HOUR)} hours` : `${Math.max(0, Math.floor(ms / 60_000))} minutes`);
98
+
99
+ /** Returns the exit code. The default dependencies are the real ones; tests pass their own. */
100
+ export async function refreshLogin({
101
+ env = process.env,
102
+ now = Date.now,
103
+ log = console.log,
104
+ refresh = () => forceRefresh({ env }),
105
+ appToken = () => getAppToken({ env: { ...env, TOKEN_SCOPE: "login" }, log }),
106
+ save = (token) => spawnSync("bash", [join(env.GITHUB_ACTION_PATH, "packages/mergelight/scripts/save-login.sh")], { stdio: "inherit", env: { ...env, SECRETS_TOKEN: token } }).status,
107
+ } = {}) {
108
+ const file = join(env.CODEX_HOME, "auth.json");
109
+ const read = () => {
110
+ try {
111
+ return JSON.parse(readFileSync(file, "utf8"));
112
+ } catch {
113
+ return null;
114
+ }
115
+ };
116
+ const before = read();
117
+ if (!before) {
118
+ log("::warning::The saved Codex login isn't valid JSON, so it can't be refreshed.");
119
+ return 0;
120
+ }
121
+ if (!before.tokens?.refresh_token) {
122
+ log("This Codex login has no refresh token, so there's nothing to refresh.");
123
+ return 0;
124
+ }
125
+ const event = env.GITHUB_EVENT_NAME;
126
+ const expiry = accessTokenExpiry(before);
127
+ if (!isDue(event, expiry, now())) {
128
+ log(expiry === null ? "Leaving the Codex login to Codex: its expiry can't be read." : `The Codex login is good for another ${left(expiry - now())}.`);
129
+ return 0;
130
+ }
131
+
132
+ // Refreshing uses up the saved refresh token, so never do it without somewhere to save the new one.
133
+ const token = env.SECRETS_TOKEN || (await appToken());
134
+ if (!token) {
135
+ const message = `The Codex login is due for a refresh, but there's nowhere to save a new one. Install the Mergelight AI app and add "id-token: write".`;
136
+ // Nobody reads a warning on a green scheduled job, and the login would run out with no sign. A review can still work.
137
+ if (event === "schedule" || event === "workflow_dispatch") {
138
+ log(`::error::${message}`);
139
+ return 1;
140
+ }
141
+ log(`::warning::${message}`);
142
+ return 0;
143
+ }
144
+
145
+ const reason = await refresh();
146
+ const after = read()?.tokens;
147
+ if (after?.refresh_token && after.access_token && after.access_token !== before.tokens.access_token) {
148
+ maskLogin({ env, log });
149
+ log("Refreshed the Codex login.");
150
+ if (save(token) !== 0) log("::warning::Couldn't save the refreshed Codex login yet. This run tries again when it ends.");
151
+ return 0;
152
+ }
153
+
154
+ if (event === "schedule" || event === "workflow_dispatch") {
155
+ log(`::error::Couldn't refresh the Codex login${reason ? ` (${reason})` : ""}. If this keeps failing, it has stopped working: delete the ${env.SECRET_NAME} secret, and the next pull request shows a code to connect ChatGPT again.`);
156
+ return 1;
157
+ }
158
+ // Probably another run refreshed it a while ago. The access token still works, so use what's left of it.
159
+ if (expiry !== null && expiry - now() > CARRY_ON_ABOVE) {
160
+ log(`::warning::Couldn't refresh the Codex login${reason ? ` (${reason})` : ""}, so another run may have done it already. This review carries on, since the login is good for another ${left(expiry - now())}.`);
161
+ return 0;
162
+ }
163
+ // Codex would try the same used token, once per reviewer, so don't start it.
164
+ log(`::error::Couldn't refresh the Codex login${reason ? ` (${reason})` : ""}.`);
165
+ appendFileSync(env.GITHUB_ENV, "MERGELIGHT_LOGIN_LOST=1\n");
166
+ return 0;
167
+ }
168
+
169
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
170
+ process.exitCode = await refreshLogin();
171
+ }
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env bash
2
+ # Saves a Claude login made during this run as the repository's secret, so the next run has it.
3
+ # Run from action.yml, which sets MERGELIGHT_CLAUDE_TOKEN, RUNNER_TEMP and optionally SECRETS_TOKEN.
4
+ set -euo pipefail
5
+
6
+ [ -n "${MERGELIGHT_CLAUDE_TOKEN:-}" ] || exit 0
7
+
8
+ token="${SECRETS_TOKEN:-}"
9
+ if [ -z "$token" ]; then
10
+ out="$RUNNER_TEMP/mergelight-login-token"
11
+ : > "$out"
12
+ TOKEN_SCOPE=login GITHUB_OUTPUT="$out" node "$GITHUB_ACTION_PATH/packages/mergelight/scripts/app-token.mjs"
13
+ token="$(sed -n 's/^token=//p' "$out")"
14
+ rm -f "$out"
15
+ fi
16
+
17
+ if [ -n "$token" ]; then
18
+ printf '%s' "$MERGELIGHT_CLAUDE_TOKEN" | GH_TOKEN="$token" gh secret set CLAUDE_CODE_OAUTH_TOKEN --repo "$GITHUB_REPOSITORY"
19
+ echo "Saved the Claude login to CLAUDE_CODE_OAUTH_TOKEN."
20
+ else
21
+ echo "::warning::Claude connected, but the login couldn't be saved, so the next run asks again. Install the Mergelight AI app and add \"id-token: write\"."
22
+ fi