@mergelight/cli 0.1.18 → 0.1.20

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.
@@ -18,14 +18,93 @@ import { getAppToken } from "./app-token.mjs";
18
18
  import { maskLogin } from "./mask-login.mjs";
19
19
 
20
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;
21
+ /**
22
+ * Longer than a review's 45 minute job limit, so Codex won't need to refresh during one. And as long as
23
+ * the jobs wait for (action.yml): a login the jobs leave alone, as it runs out too soon, is one the
24
+ * review refreshes in the same run.
25
+ */
26
+ export const REVIEW_WITHIN = 2.5 * HOUR;
23
27
  /**
24
28
  * A review that lost the race needs its token to outlast it, because Codex would try the used refresh
25
29
  * token in the token's last 5 minutes. Most reviews finish well inside this.
26
30
  */
27
31
  const CARRY_ON_ABOVE = 20 * 60_000;
28
32
 
33
+ /** The command that saves a ChatGPT login of its own as this repository's secret, as setup's codexLogin() makes one. */
34
+ export function ownLoginCommand(secret = "CODEX_AUTH_JSON", repo = "OWNER/REPO") {
35
+ return `d="$(mktemp -d)" && echo 'cli_auth_credentials_store = "file"' > "$d/config.toml" && CODEX_HOME="$d" codex login && gh secret set ${secret} --repo ${repo} < "$d/auth.json" && echo "Saved the ChatGPT login in ${repo}."; s=$?; [ -n "$d" ] && rm -rf "$d"; (exit $s)`;
36
+ }
37
+
38
+ /**
39
+ * When the pull request event that started this run happened, in seconds, or null when it isn't one. Only
40
+ * on the run's first attempt: a run started again keeps the first attempt's event, but gets the secrets
41
+ * as they are when it starts again.
42
+ */
43
+ export function eventTime(env = process.env) {
44
+ if (Number(env.GITHUB_RUN_ATTEMPT || 1) > 1) return null;
45
+ try {
46
+ const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, "utf8"));
47
+ const time = Date.parse(event?.pull_request?.updated_at ?? "");
48
+ return Number.isFinite(time) ? Math.floor(time / 1000) : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * The GitHub environment this job runs in, from GitHub's signed pass for the run: "" for none, null when
56
+ * the job can't get a pass (no "id-token: write"), and undefined when GitHub didn't give one this time.
57
+ * An environment's secret wins over the repository's of the same name, so the login may be the
58
+ * environment's.
59
+ */
60
+ export async function jobEnvironment({ env = process.env, fetchImpl = fetch } = {}) {
61
+ if (!env.ACTIONS_ID_TOKEN_REQUEST_URL || !env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) return null;
62
+ try {
63
+ const url = new URL(env.ACTIONS_ID_TOKEN_REQUEST_URL);
64
+ url.searchParams.set("audience", "mergelight-login-check");
65
+ const res = await fetchImpl(url, { headers: { authorization: `Bearer ${env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` } });
66
+ if (res.status !== 200) return undefined;
67
+ const { value } = await res.json();
68
+ const claims = JSON.parse(Buffer.from(String(value).split(".")[1], "base64url").toString("utf8"));
69
+ return typeof claims.environment === "string" ? claims.environment : "";
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Whether the login this run has is this repository's own secret, as last saved. For a job in no GitHub
77
+ * environment: an environment's secret would win over the repository's.
78
+ * - "no": the repository has no secret of that name, so the login comes from elsewhere, such as an
79
+ * organization's secret. A refresh saved here would leave that secret holding a spent refresh token,
80
+ * and sign out every repository that shares it.
81
+ * - "newer": the secret was saved again after this run got it, by another run or a person, so what this
82
+ * run has may not be what the repository holds. When it got it is taken early: the login step's time
83
+ * less ten minutes (MERGELIGHT_LOGIN_READ_AT), or the pull request event's time when that is earlier,
84
+ * as the run and its secrets come after the event. A login this run saved itself counts from then
85
+ * (MERGELIGHT_LOGIN_SAVED_AT).
86
+ * - "unknown": GitHub didn't answer plainly.
87
+ */
88
+ export async function secretHeld({ env = process.env, token, fetchImpl = fetch } = {}) {
89
+ const api = env.GITHUB_API_URL || "https://api.github.com";
90
+ const name = encodeURIComponent(env.SECRET_NAME || "CODEX_AUTH_JSON");
91
+ const headers = { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" };
92
+ try {
93
+ const res = await fetchImpl(`${api}/repos/${env.GITHUB_REPOSITORY}/actions/secrets/${name}`, { headers });
94
+ if (res.status === 404) return "no";
95
+ if (res.status !== 200) return "unknown";
96
+ const read = Number(env.MERGELIGHT_LOGIN_READ_AT);
97
+ const event = eventTime(env);
98
+ const since = Number(env.MERGELIGHT_LOGIN_SAVED_AT) || (read && event !== null ? Math.min(read, event) : read);
99
+ if (!since) return "yes";
100
+ const updated = Date.parse((await res.json())?.updated_at ?? "");
101
+ if (!Number.isFinite(updated)) return "unknown";
102
+ return updated / 1000 > since ? "newer" : "yes";
103
+ } catch {
104
+ return "unknown";
105
+ }
106
+ }
107
+
29
108
  /** When the login's access token expires, in milliseconds, or null if that can't be told. */
30
109
  export function accessTokenExpiry(auth) {
31
110
  try {
@@ -103,6 +182,8 @@ export async function refreshLogin({
103
182
  log = console.log,
104
183
  refresh = () => forceRefresh({ env }),
105
184
  appToken = () => getAppToken({ env: { ...env, TOKEN_SCOPE: "login" }, log }),
185
+ held = (token) => secretHeld({ env, token }),
186
+ environment = () => jobEnvironment({ env }),
106
187
  save = (token) => spawnSync("bash", [join(env.GITHUB_ACTION_PATH, "packages/mergelight/scripts/save-login.sh")], { stdio: "inherit", env: { ...env, SECRETS_TOKEN: token } }).status,
107
188
  } = {}) {
108
189
  const file = join(env.CODEX_HOME, "auth.json");
@@ -142,12 +223,50 @@ export async function refreshLogin({
142
223
  return 0;
143
224
  }
144
225
 
226
+ // A login other repositories share is never refreshed here: the new one could only be saved to this
227
+ // repository, and the shared secret would keep a spent refresh token.
228
+ // Refreshed only once known to be the repository's own, as last saved. Otherwise the refresh could spend
229
+ // a token that other repositories or an environment's other jobs share, or the save replace a newer
230
+ // login. Such a login isn't used either, even with time left: Codex refreshes a login by itself in its
231
+ // last minutes, which a long job can reach. No sign-in waits on it.
232
+ const secret = env.SECRET_NAME || "CODEX_AUTH_JSON";
233
+ // An environment's secret of the same name wins over the repository's, and can't be read with the
234
+ // token that saves the login: a job in an environment, or one that can't be told, isn't refreshed.
235
+ const where = await environment();
236
+ const owned = where === null ? "blind" : where === undefined ? "unknown" : where ? "environment" : await held(token);
237
+ if (owned !== "yes") {
238
+ const message = {
239
+ no: `This repository reads its ChatGPT login from a ${secret} secret it doesn't hold itself, such as an organization's. Mergelight doesn't refresh a login other repositories share, as that would sign them out. Save a login of its own as this repository's secret, then push: \`${ownLoginCommand(secret, env.GITHUB_REPOSITORY)}\``,
240
+ environment: `This job runs in the GitHub environment "${where}", whose own ${secret} secret would win over the repository's, so Mergelight can't tell whose ChatGPT login this is and doesn't refresh it, as that could sign out the environment's other jobs. Remove environment: from the Mergelight job, and keep the login as the repository's own secret.`,
241
+ blind: `Mergelight can't tell whether this job runs in a GitHub environment, whose secret would win over the repository's, so it doesn't refresh the ChatGPT login. Add "id-token: write" to the job's permissions, then push.`,
242
+ newer: `The ${secret} secret was saved again after this run got it, so this run doesn't refresh or use the ChatGPT login it has. Run the Mergelight job again, or push a new commit: the next run gets the secret as it is then.`,
243
+ unknown: `GitHub couldn't say whether this repository holds the ${secret} secret itself, so this run doesn't refresh or use the ChatGPT login. Nothing is wrong with the login: run the Mergelight job again.`,
244
+ }[owned];
245
+ if (event === "schedule" || event === "workflow_dispatch") {
246
+ // A newer one is there already: nothing for the job to do.
247
+ if (owned === "newer") {
248
+ log(message);
249
+ return 0;
250
+ }
251
+ log(`::error::${message}`);
252
+ return 1;
253
+ }
254
+ log(`::error::${message}`);
255
+ // The review says the same, also when Codex only checks.
256
+ if (env.GITHUB_ENV) appendFileSync(env.GITHUB_ENV, `MERGELIGHT_LOGIN_SHORT=1\nMERGELIGHT_LOGIN_LOST=1\nMERGELIGHT_LOGIN_NOTE=${message}\n`);
257
+ return 0;
258
+ }
259
+
145
260
  const reason = await refresh();
146
261
  const after = read()?.tokens;
147
262
  if (after?.refresh_token && after.access_token && after.access_token !== before.tokens.access_token) {
148
263
  maskLogin({ env, log });
149
264
  log("Refreshed the Codex login.");
265
+ // A refresh that failed earlier in this run no longer stops the review, nor holds a sign-in back.
266
+ if (env.GITHUB_ENV) appendFileSync(env.GITHUB_ENV, "MERGELIGHT_LOGIN_LOST=0\nMERGELIGHT_LOGIN_SHORT=0\n");
150
267
  if (save(token) !== 0) log("::warning::Couldn't save the refreshed Codex login yet. This run tries again when it ends.");
268
+ // Saved by this run: the secret is this run's own again, as of now.
269
+ else if (env.GITHUB_ENV) appendFileSync(env.GITHUB_ENV, `MERGELIGHT_LOGIN_SAVED_AT=${Math.floor(now() / 1000)}\n`);
151
270
  return 0;
152
271
  }
153
272
 
@@ -158,6 +277,8 @@ export async function refreshLogin({
158
277
  // Probably another run refreshed it a while ago. The access token still works, so use what's left of it.
159
278
  if (expiry !== null && expiry - now() > CARRY_ON_ABOVE) {
160
279
  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())}.`);
280
+ // What's left is for the review: nothing else in this run may wait on it, as the checker's sign-in would.
281
+ if (env.GITHUB_ENV) appendFileSync(env.GITHUB_ENV, "MERGELIGHT_LOGIN_SHORT=1\n");
161
282
  return 0;
162
283
  }
163
284
  // Codex would try the same used token, once per reviewer, so don't start it.
@@ -3,6 +3,8 @@
3
3
  # Run from action.yml, which sets CODEX_HOME, RUNNER_TEMP, SECRET_NAME and optionally SECRETS_TOKEN.
4
4
  set -euo pipefail
5
5
 
6
+ # Only the login this Action set up: a CODEX_HOME from anywhere else, such as a runner's own account, is never saved.
7
+ [ "${CODEX_HOME:-}" = "$RUNNER_TEMP/codex-home" ] || exit 0
6
8
  auth="$CODEX_HOME/auth.json"
7
9
  seen="$RUNNER_TEMP/codex-auth.sha256"
8
10
  [ -f "$auth" ] || exit 0
@@ -0,0 +1,137 @@
1
+ # Mergelight review, with your team's jobs. It runs in your GitHub Actions, on your AI plan.
2
+ # Use it in place of mergelight.yml. Jobs are tasks you write in .mergelight/jobs: on each pull request
3
+ # that needs one, the AI does it and Mergelight pushes one commit to the pull request's branch.
4
+ # See https://github.com/mergelightai/mergelight/blob/main/docs/jobs.md
5
+ name: Mergelight
6
+
7
+ on:
8
+ pull_request:
9
+ types: [opened, synchronize, reopened, ready_for_review, edited]
10
+ # A comment that mentions @mergelight-ai on a pull request reviews it again, reading the comment as your
11
+ # team's answer to the findings: what's fixed, and what to leave and why. Only people who can push count.
12
+ issue_comment:
13
+ types: [created]
14
+
15
+ # Each job says what it may do. Only push-jobs may push, and it runs no AI.
16
+ permissions: {}
17
+
18
+ # A new push cancels the older run of the same pull request. An edit that changes only the title or
19
+ # description starts nothing, so it gets a group of its own and never cancels a run that is working.
20
+ # So does every comment: one that doesn't mention Mergelight starts nothing either. A run started again
21
+ # by hand waits for the one going instead of cancelling it.
22
+ concurrency:
23
+ group: mergelight-pr-${{ github.event.pull_request.number || github.event.issue.number }}${{ github.event_name == 'issue_comment' && format('-comment-{0}', github.event.comment.id) || ((github.event.action == 'edited' && !github.event.changes.base) && '-edit' || '') }}
24
+ cancel-in-progress: ${{ github.run_attempt == 1 }}
25
+
26
+ jobs:
27
+ # The AI does the jobs, with a token that can only read, and writes what they changed to a file.
28
+ run-jobs:
29
+ # Forks and Dependabot get no secrets, and drafts aren't ready. An edit only counts when the target
30
+ # branch changed, so a new title starts nothing. A comment runs no jobs.
31
+ if: >
32
+ github.event_name == 'pull_request' &&
33
+ (github.event.action != 'edited' || github.event.changes.base) &&
34
+ !github.event.pull_request.draft &&
35
+ github.actor != 'dependabot[bot]' &&
36
+ github.event.pull_request.head.repo.full_name == github.repository
37
+ runs-on: ubuntu-latest
38
+ timeout-minutes: 30
39
+ permissions:
40
+ contents: read
41
+ pull-requests: read
42
+ id-token: write # Lets it save a refreshed ChatGPT login through the Mergelight AI app, if installed.
43
+ outputs:
44
+ changes: ${{ steps.jobs.outputs.jobs-changes }}
45
+ steps:
46
+ # Not pinned, on purpose. @v0 moves to each new release, so fixes reach you without
47
+ # merging anything. The catch: this step can read your AI login, so you're trusting each
48
+ # release as it comes. To check every update yourself, pin it with the line from a release:
49
+ # https://github.com/mergelightai/mergelight/releases
50
+ - uses: mergelightai/mergelight@v0
51
+ id: jobs
52
+ with:
53
+ run: jobs
54
+ # Jobs is part of a paid plan. Mergelight's server says whether your org's plan includes it.
55
+ # It is shown GitHub's signed pass for the run, which names the repository, branch, workflow
56
+ # and who started it. Nothing about your code is sent.
57
+ server: https://mergelight-server.onrender.com
58
+ codex-auth-json: ${{ secrets.CODEX_AUTH_JSON }}
59
+ openai-api-key: ${{ secrets.OPENAI_API_KEY }}
60
+ claude-code-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
61
+ anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
62
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
63
+ # Also when every job failed: the result says why, for the review's summary.
64
+ if: ${{ !cancelled() && steps.jobs.outputs.jobs-result != '' }}
65
+ with:
66
+ name: mergelight-jobs
67
+ path: ${{ steps.jobs.outputs.jobs-result }}
68
+ retention-days: 1
69
+ if-no-files-found: ignore
70
+ # Run again, the run's file from the first try is replaced, not a reason to fail.
71
+ overwrite: true
72
+
73
+ # No AI and no AI login: checks the file again against your jobs, and pushes one commit.
74
+ push-jobs:
75
+ needs: run-jobs
76
+ if: needs.run-jobs.outputs.changes != '' && needs.run-jobs.outputs.changes != '0'
77
+ runs-on: ubuntu-latest
78
+ timeout-minutes: 10
79
+ permissions:
80
+ contents: write
81
+ pull-requests: read
82
+ outputs:
83
+ commit: ${{ steps.push.outputs.commit }}
84
+ why: ${{ steps.push.outputs.why }}
85
+ steps:
86
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
87
+ with:
88
+ name: mergelight-jobs
89
+ path: ${{ runner.temp }}/mergelight-jobs
90
+ - uses: mergelightai/mergelight/push-jobs@v0
91
+ id: push
92
+ with:
93
+ result: ${{ runner.temp }}/mergelight-jobs/mergelight-jobs.json
94
+
95
+ # The review, as in mergelight.yml, of the commit the jobs pushed when they pushed one.
96
+ review:
97
+ needs: [run-jobs, push-jobs]
98
+ # Also after jobs that failed or had nothing to push, but not in a run a newer push cancelled. A comment
99
+ # counts when it mentions Mergelight on a pull request, and isn't a bot's.
100
+ if: >
101
+ !cancelled() &&
102
+ ((github.event_name == 'issue_comment' &&
103
+ github.event.issue.pull_request &&
104
+ contains(github.event.comment.body, '@mergelight-ai') &&
105
+ github.event.comment.user.type != 'Bot') ||
106
+ (github.event_name == 'pull_request' &&
107
+ (github.event.action != 'edited' || github.event.changes.base) &&
108
+ !github.event.pull_request.draft &&
109
+ github.actor != 'dependabot[bot]' &&
110
+ github.event.pull_request.head.repo.full_name == github.repository))
111
+ runs-on: ubuntu-latest
112
+ # Room for the first login, which can wait up to 16 minutes, and then a long review.
113
+ timeout-minutes: 45
114
+ permissions:
115
+ contents: read
116
+ pull-requests: write
117
+ checks: write
118
+ id-token: write # Lets it post as the Mergelight AI app, if installed.
119
+ steps:
120
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
121
+ # No file when no job ran. Not when the jobs didn't run in this try: a file from an earlier try
122
+ # would tell about other jobs.
123
+ if: needs.run-jobs.result != 'skipped'
124
+ continue-on-error: true
125
+ with:
126
+ name: mergelight-jobs
127
+ path: ${{ runner.temp }}/mergelight-jobs
128
+ - uses: mergelightai/mergelight@v0
129
+ with:
130
+ codex-auth-json: ${{ secrets.CODEX_AUTH_JSON }}
131
+ openai-api-key: ${{ secrets.OPENAI_API_KEY }}
132
+ claude-code-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
133
+ anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
134
+ commit: ${{ needs.push-jobs.outputs.commit }}
135
+ jobs-result: ${{ runner.temp }}/mergelight-jobs/mergelight-jobs.json
136
+ jobs-commit: ${{ needs.push-jobs.outputs.commit }}
137
+ jobs-why: ${{ needs.push-jobs.outputs.why }}
@@ -5,6 +5,10 @@ name: Mergelight
5
5
  on:
6
6
  pull_request:
7
7
  types: [opened, synchronize, reopened, ready_for_review, edited]
8
+ # A comment that mentions @mergelight-ai on a pull request reviews it again, reading the comment as your
9
+ # team's answer to the findings: what's fixed, and what to leave and why. Only people who can push count.
10
+ issue_comment:
11
+ types: [created]
8
12
 
9
13
  permissions:
10
14
  contents: read
@@ -15,18 +19,25 @@ permissions:
15
19
  jobs:
16
20
  review:
17
21
  # Forks and Dependabot get no secrets, and drafts aren't ready for review. An edit only counts when the
18
- # target branch changed, so a new title doesn't start a review.
22
+ # target branch changed, so a new title doesn't start a review. A comment counts when it mentions
23
+ # Mergelight on a pull request, and isn't a bot's.
19
24
  if: >
25
+ (github.event_name == 'issue_comment' &&
26
+ github.event.issue.pull_request &&
27
+ contains(github.event.comment.body, '@mergelight-ai') &&
28
+ github.event.comment.user.type != 'Bot') ||
29
+ (github.event_name == 'pull_request' &&
20
30
  (github.event.action != 'edited' || github.event.changes.base) &&
21
31
  !github.event.pull_request.draft &&
22
32
  github.actor != 'dependabot[bot]' &&
23
- github.event.pull_request.head.repo.full_name == github.repository
33
+ github.event.pull_request.head.repo.full_name == github.repository)
24
34
  runs-on: ubuntu-latest
25
35
  # Room for the first login, which can wait up to 16 minutes, and then a long review.
26
36
  timeout-minutes: 45
27
- # A new push cancels the older review of the same PR.
37
+ # A new push cancels the older review of the same PR. A comment's review has a group of its own, so
38
+ # neither cancels the other.
28
39
  concurrency:
29
- group: mergelight-pr-${{ github.event.pull_request.number }}
40
+ group: mergelight-pr-${{ github.event.pull_request.number || github.event.issue.number }}${{ github.event_name == 'issue_comment' && format('-comment-{0}', github.event.comment.id) || '' }}
30
41
  cancel-in-progress: true
31
42
  steps:
32
43
  # Not pinned, on purpose. @v0 moves to each new release, so fixes reach you without