@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.
package/dist/answer.js ADDED
@@ -0,0 +1,85 @@
1
+ import { RESOLVED_ONLY } from "./prompt.js";
2
+ import { encodeMark, MAX_NOTE } from "./publish/handled.js";
3
+ import { withoutHidden } from "./skills.js";
4
+ /** Enough for a long answer to every finding of a round, and no wall that crowds out the code. */
5
+ export const MAX_ANSWER = 8_000;
6
+ /** The comment that started this run, as the Action passes it on. Null when no comment did. */
7
+ export function teamAnswerFromEnv(env = process.env) {
8
+ const by = env.MERGELIGHT_COMMENT_BY?.trim();
9
+ const text = withoutHidden(env.MERGELIGHT_COMMENT_BODY ?? "").trim();
10
+ if (!by || !text || !/^[\w.-]{1,100}$/.test(by))
11
+ return null;
12
+ return { by, at: env.MERGELIGHT_COMMENT_AT ?? new Date().toISOString(), url: env.MERGELIGHT_COMMENT_URL ?? "", text: text.slice(0, MAX_ANSWER) };
13
+ }
14
+ /**
15
+ * How the verifier names a finding the answer decided to leave: "the team decided not to fix this: <their
16
+ * reason>". The bare form is for a decision made before, so it is no new one.
17
+ */
18
+ const DECIDED = /^\s*the team decided not to fix this\s*:\s*(\S.*)$/is;
19
+ /**
20
+ * The earlier findings the verifier left because the team's answer decided so, each with the team's
21
+ * reason as the verifier put it. Only earlier findings: a candidate isn't the team's to decide on.
22
+ */
23
+ export function decisionsFromAnswer(previous, rejected) {
24
+ const earlier = new Map((previous ?? []).map((p) => [p.id, p]));
25
+ const decided = new Map();
26
+ for (const r of rejected) {
27
+ const p = earlier.get(r.candidate);
28
+ const m = DECIDED.exec(r.reason);
29
+ // A finding someone decided on before, with a reason, keeps their decision and their name. A thread
30
+ // resolved without a word gets its reason from the answer.
31
+ const reasoned = p?.handled?.as === "wont_fix" && Boolean(p.handled.note) && p.handled.note !== RESOLVED_ONLY;
32
+ if (!p || !m || decided.has(p.id) || reasoned)
33
+ continue;
34
+ decided.set(p.id, { id: p.id, title: p.title, note: m[1].replace(/\s+/g, " ").trim() });
35
+ }
36
+ return [...decided.values()];
37
+ }
38
+ /**
39
+ * The decisions as the team's own: the next steps read them like a mark the person wrote, so the
40
+ * server can keep their reasons for later pull requests.
41
+ */
42
+ export function withDecisions(previous, decided, answer, sha) {
43
+ if (!decided.length)
44
+ return previous;
45
+ const notes = new Map(decided.map((d) => [d.id, d.note]));
46
+ return previous?.map((p) => (notes.has(p.id) ? { ...p, handled: { as: "wont_fix", note: notes.get(p.id), by: answer.by, sha, from: "mark", at: answer.at } } : p));
47
+ }
48
+ /** A finding's title as one plain line, safe inside a list. */
49
+ function line(text) {
50
+ return text
51
+ .replace(/\s+/g, " ")
52
+ .replace(/<!--/g, "&lt;!--")
53
+ .replace(/(^|[^\w`])@(?=[A-Za-z0-9-])/g, "$1@​")
54
+ .trim();
55
+ }
56
+ /**
57
+ * Mergelight's answer to the comment: what it took from it, and what still holds the merge. Each
58
+ * decision is kept as a mark of its own, with the team's reason, so later rounds and the agent tools
59
+ * read it like any other. Never names Mergelight with an @, so it can't start another run.
60
+ */
61
+ export function answerReplyBody(answer, decided, review, sha) {
62
+ const holding = review.findings.filter((f) => f.tier !== "hardening");
63
+ const out = [`Read the answer from ${line(answer.by)}${answer.url ? ` ([comment](${answer.url}))` : ""}.`];
64
+ if (decided.length) {
65
+ out.push("", `**Left as the team decided (${decided.length}):** these don't come back.`);
66
+ for (const d of decided)
67
+ out.push(`- ${line(d.title)}: ${line(d.note)}`);
68
+ }
69
+ else {
70
+ out.push("", "Nothing in it decided to leave a finding as it is.");
71
+ }
72
+ if (holding.length) {
73
+ out.push("", `**Still holds the merge (${holding.length}):**`);
74
+ for (const f of holding)
75
+ out.push(`- ${line(f.title)}: ${line(f.verdict)}`);
76
+ }
77
+ else {
78
+ // A team check, or a guarded file, can still hold it: the summary and the checks say.
79
+ out.push("", "No finding holds the merge now. The summary and the checks show anything else that does.");
80
+ }
81
+ out.push("", "The summary is up to date.");
82
+ for (const d of decided)
83
+ out.push(encodeMark([d.id], "wont_fix", `${answer.by}: ${d.note}`.slice(0, MAX_NOTE), sha));
84
+ return out.join("\n");
85
+ }
package/dist/cli.js CHANGED
@@ -1,17 +1,22 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
4
  import { currentRepo, fetchPullRequest, parsePrRef } from "./github.js";
5
5
  import { serve } from "./mcp/server.js";
6
6
  import { declinesOf, fetchContext, MAX_REASON, reportReview } from "./cloud.js";
7
7
  import { GitHub } from "./publish/api.js";
8
- import { writeAccess } from "./publish/handled.js";
8
+ import { askWriteAccess, writeAccess } from "./publish/handled.js";
9
+ import { answerReplyBody, decisionsFromAnswer, teamAnswerFromEnv, withDecisions } from "./answer.js";
9
10
  import { publishTeamChecks } from "./publish/team-checks.js";
10
- import { answerRemembered, confirmReasons, approveCheck, checkLimitTitle, checkLoginTitle, failCheck, failSummary, previousFindings, publishReview, startCheck, startSummary, syncApproval, UNREVIEWED, APPROVALS_OFF, updatePendingSummary } from "./publish/publish.js";
11
- import { configuredModel, LimitError, LoginError, loginFailureMessage } from "./providers/codex.js";
12
- import { limitNotice, loginNotice } from "./publish/markdown.js";
11
+ import { answerRemembered, confirmReasons, approveCheck, checkHeldTitle, checkLimitTitle, checkLoginTitle, failCheck, failSummary, previousReview, publishReview, startCheck, startSummary, syncApproval, UNREVIEWED, APPROVALS_OFF, updatePendingSummary } from "./publish/publish.js";
12
+ import { configuredModel, HeldLoginError, LimitError, LoginError, loginFailureMessage } from "./providers/codex.js";
13
+ import { heldLoginNotice, limitNotice, loginNotice } from "./publish/markdown.js";
13
14
  import { renderRejected, renderTerminal } from "./render.js";
14
15
  import { reviewPullRequest } from "./review.js";
16
+ import { jobsCommand } from "./jobs-command.js";
17
+ import { pushJobs } from "./push-jobs.js";
18
+ import { CURRENT } from "./update.js";
19
+ import { jobsReport } from "./run-jobs.js";
15
20
  import { askForApp, connect, githubConnect } from "./connect.js";
16
21
  import { init, realInitDeps } from "./init.js";
17
22
  import { realDeps, setup } from "./setup.js";
@@ -25,6 +30,11 @@ Usage
25
30
  mergelight mcp Run the MCP server, so your coding agent can read findings
26
31
  mergelight setup <owner/repo> Set up the GitHub Action on a repository
27
32
  mergelight connect <pr> In the Action: connect ChatGPT from the pull request
33
+ mergelight jobs <pr> [--out <file>] Run the team's jobs from .mergelight/jobs on a pull request, and
34
+ write what they changed to a file. Nothing is pushed or posted
35
+ mergelight push-jobs <pr> --from <file>
36
+ Check a jobs file again against the base branch, and push it as
37
+ one commit to the pull request's branch. Runs no AI
28
38
 
29
39
  <pr> is a pull request URL, owner/repo#123, or a number inside a clone.
30
40
 
@@ -43,7 +53,12 @@ Options
43
53
  --effort <level> Reasoning effort: low, medium, high (default: high)
44
54
  --verify-with <name> Who checks the findings: claude or codex
45
55
  (default: claude when Claude Code is installed)
56
+ --verify-missed <name>
57
+ The AI that was meant to check but had no login: the summary says so
46
58
  --verify-model <name> Model for the checker (default for claude: opus)
59
+ --jobs <file> With --post: the file mergelight jobs wrote, for the Jobs part of the summary
60
+ --jobs-commit <sha> With --jobs: the commit the push step made. It is the one reviewed
61
+ --jobs-why <text> With --jobs: why the push step pushed nothing
47
62
  --keep Keep the temporary checkout
48
63
  --by <login> Who approved, for approve
49
64
  With approve, --at is the commit they approved: an older one doesn't count
@@ -51,9 +66,14 @@ Options
51
66
  --skip-branches <a,b> For setup: don't review pull requests from these branches
52
67
  --relogin For setup: log in to Codex again
53
68
  --no-pin For setup: follow @v0 and get each release by itself, instead of pinning to the latest
69
+ --with-jobs For setup: also run the team's jobs from .mergelight/jobs (see docs/jobs.md)
54
70
  --yes For setup: don't stop to ask whether the app is installed
55
71
  --no-save For connect: there's nowhere to save a login, so ask for the app instead
72
+ --for check --ai <name> --reviewer <name>
73
+ For connect: connect the AI that checks another AI's review. Nobody
74
+ connecting it holds nothing up: the reviewer checks instead
56
75
  -h, --help Show this help
76
+ -v, --version Show the version
57
77
 
58
78
  Reviews run on your own logged-in Codex CLI, and Claude Code if you check with it.
59
79
  Your code and your AI login are never sent to Mergelight.
@@ -89,8 +109,17 @@ function progressPrinter() {
89
109
  };
90
110
  }
91
111
  const log = (line) => process.stderr.write(`${line}\n`);
112
+ /** parseArgs throws on an option it doesn't know, like a typo. That gets one line, not a stack trace. */
113
+ function argsOrError(read) {
114
+ try {
115
+ return read();
116
+ }
117
+ catch (err) {
118
+ return err instanceof Error ? err : new Error(String(err));
119
+ }
120
+ }
92
121
  async function main() {
93
- const { values, positionals } = parseArgs({
122
+ const parsed = argsOrError(() => parseArgs({
94
123
  allowPositionals: true,
95
124
  options: {
96
125
  repo: { type: "string" },
@@ -113,12 +142,33 @@ async function main() {
113
142
  relogin: { type: "boolean" },
114
143
  pin: { type: "boolean" },
115
144
  "no-pin": { type: "boolean" },
145
+ "with-jobs": { type: "boolean" },
116
146
  yes: { type: "boolean" },
117
147
  "no-save": { type: "boolean" },
148
+ for: { type: "string" },
149
+ ai: { type: "string" },
150
+ reviewer: { type: "string" },
151
+ "verify-missed": { type: "string" },
152
+ "verify-missed-why": { type: "string" },
153
+ from: { type: "string" },
154
+ jobs: { type: "string" },
155
+ "jobs-commit": { type: "string" },
156
+ "jobs-why": { type: "string" },
118
157
  help: { type: "boolean", short: "h" },
158
+ version: { type: "boolean", short: "v" },
119
159
  },
120
- });
160
+ }));
161
+ if (parsed instanceof Error) {
162
+ // Node's message goes on to explain "--" for positionals, which helps nobody here: the first sentence says it.
163
+ log(`mergelight: ${(parsed.message.split(/\.\s/)[0] ?? parsed.message).replace(/\.$/, "")}. Run mergelight --help to see the options.`);
164
+ return 1;
165
+ }
166
+ const { values, positionals } = parsed;
121
167
  const [command, target] = positionals;
168
+ if (values.version) {
169
+ process.stdout.write(`${CURRENT}\n`);
170
+ return 0;
171
+ }
122
172
  if (values.help || !command) {
123
173
  process.stdout.write(HELP);
124
174
  return values.help ? 0 : 1;
@@ -135,6 +185,7 @@ async function main() {
135
185
  skipBranches: values["skip-branches"]?.split(",").map((b) => b.trim()).filter(Boolean),
136
186
  relogin: values.relogin,
137
187
  pin: !values["no-pin"],
188
+ jobs: values["with-jobs"],
138
189
  yes: values.yes,
139
190
  }, realDeps());
140
191
  }
@@ -156,7 +207,7 @@ async function main() {
156
207
  await serve();
157
208
  return 0;
158
209
  }
159
- if (!["review", "post", "approve", "connect"].includes(command) || !target) {
210
+ if (!["review", "post", "approve", "connect", "jobs", "push-jobs"].includes(command) || !target) {
160
211
  process.stderr.write(HELP);
161
212
  return 1;
162
213
  }
@@ -171,6 +222,12 @@ async function main() {
171
222
  log(`mergelight: --verify-with must be codex or claude, not "${verifyWith}"`);
172
223
  return 1;
173
224
  }
225
+ // The AI the team asked to check, which had no login, so the reviewer's own AI checked instead.
226
+ const verifyMissed = values["verify-missed"];
227
+ if (verifyMissed !== undefined && verifyMissed !== "codex" && verifyMissed !== "claude") {
228
+ log(`mergelight: --verify-missed must be codex or claude, not "${verifyMissed}"`);
229
+ return 1;
230
+ }
174
231
  if (command === "post") {
175
232
  const review = JSON.parse(readFileSync(target, "utf8"));
176
233
  const result = await publishReview(review, { dryRun, log, yellowBlocks: values["yellow-blocks"], approve: !values["no-approve"] });
@@ -178,16 +235,72 @@ async function main() {
178
235
  return 0;
179
236
  }
180
237
  const ref = parsePrRef(target, values.repo ?? (await currentRepo()));
238
+ if (command === "jobs") {
239
+ const progress = progressPrinter();
240
+ try {
241
+ // A log line clears the progress line first, so the two never run together in a terminal.
242
+ const clearing = (line) => log(process.stderr.isTTY ? `\r\x1b[2K${line}` : line);
243
+ return await jobsCommand(ref, { provider, model: values.model, effort: values.effort, out: values.out, at: values.at, keep: values.keep, log: clearing, onProgress: progress.onProgress });
244
+ }
245
+ catch (err) {
246
+ progress.stop();
247
+ log(`mergelight: ${err instanceof Error ? err.message : String(err)}`);
248
+ return 1;
249
+ }
250
+ finally {
251
+ progress.stop();
252
+ }
253
+ }
254
+ if (command === "push-jobs") {
255
+ if (!values.from) {
256
+ log("push-jobs needs --from <file>, the file mergelight jobs wrote");
257
+ return 1;
258
+ }
259
+ try {
260
+ return await pushJobs(ref, { from: values.from, dryRun, log });
261
+ }
262
+ catch (err) {
263
+ log(`mergelight: ${err instanceof Error ? err.message : String(err)}`);
264
+ return 1;
265
+ }
266
+ }
181
267
  if (command === "connect") {
268
+ // --for check: connect the AI that checks another AI's review. It never stops the review: when nobody
269
+ // connects it, or it can't be saved, the reviewer's own AI checks, and the review's summary says so.
270
+ const check = values.for === "check";
271
+ const ai = values.ai;
272
+ const reviewer = values.reviewer;
273
+ if (values.for !== undefined && values.for !== "check" && values.for !== "review") {
274
+ log(`mergelight: --for must be review or check, not "${values.for}"`);
275
+ return 1;
276
+ }
277
+ if (check && ((ai !== "codex" && ai !== "claude") || (reviewer !== "codex" && reviewer !== "claude") || ai === reviewer)) {
278
+ log("mergelight: connect --for check needs --ai and --reviewer, each codex or claude, and not the same.");
279
+ return 1;
280
+ }
281
+ // For a review, --ai claude offers only Claude's link: the workflow says Claude reviews, and it has no login yet.
282
+ if (!check && ai !== undefined && ai !== "claude") {
283
+ log(`mergelight: for a review, --ai can only be claude, not "${ai}"`);
284
+ return 1;
285
+ }
182
286
  try {
183
287
  const api = new GitHub(ref.owner, ref.repo, { log });
184
288
  const { headSha } = await fetchPullRequest(ref);
289
+ if (check) {
290
+ if (values["no-save"]) {
291
+ log(`There's nowhere to save a ${ai === "codex" ? "ChatGPT" : "Claude"} login without the Mergelight AI app, so the reviewer's own AI checks this time.`);
292
+ return 0;
293
+ }
294
+ await connect(githubConnect(api, ref.number, headSha, log, process.env, { purpose: "check", ai: ai, reviewer: reviewer }));
295
+ return 0;
296
+ }
297
+ const login = ai === "claude" ? "Claude" : "ChatGPT";
185
298
  if (values["no-save"]) {
186
- await askForApp(api, ref.number, headSha);
187
- log("Install the Mergelight AI app: without it there's nowhere to save the ChatGPT login.");
299
+ await askForApp(api, ref.number, headSha, login);
300
+ log(`Install the Mergelight AI app: without it there's nowhere to save the ${login} login.`);
188
301
  return 1;
189
302
  }
190
- return await connect(githubConnect(api, ref.number, headSha, log));
303
+ return await connect(githubConnect(api, ref.number, headSha, log, process.env, ai === "claude" ? { purpose: "review", ai: "claude" } : { purpose: "review" }));
191
304
  }
192
305
  catch (err) {
193
306
  log(`mergelight: ${err instanceof Error ? err.message : String(err)}`);
@@ -204,18 +317,76 @@ async function main() {
204
317
  }
205
318
  // review
206
319
  const api = new GitHub(ref.owner, ref.repo, { dryRun, log });
320
+ // What the team's jobs did just before: shown in the summary, and their commit is the one reviewed.
321
+ let jobs = null;
322
+ if (values.jobs) {
323
+ try {
324
+ jobs = jobsReport(JSON.parse(readFileSync(values.jobs, "utf8")), { commit: values["jobs-commit"], why: values["jobs-why"] });
325
+ }
326
+ catch (err) {
327
+ log(`Couldn't read the jobs file, so the summary leaves the jobs out: ${err.message}`);
328
+ }
329
+ }
330
+ const jobCommit = jobs?.commit ? { sha: jobs.commit, jobs: jobs.outcomes.filter((o) => o.status === "changed").map((o) => o.name) } : undefined;
331
+ // The commit the push step names is the one to review, also when the jobs file can't be read.
332
+ values.at ??= jobCommit?.sha ?? (/^[0-9a-f]{40}$/.test(values["jobs-commit"] ?? "") ? values["jobs-commit"] : undefined);
207
333
  let checkRunId = null;
208
334
  let summaryComment = null;
209
335
  /** The edit that names the models, so a result or a failure notice is always written after it. */
210
336
  let naming = Promise.resolve();
337
+ // The jobs' commit is reviewed only while it is still the pull request's newest: a review started again
338
+ // later, after more pushes, reads the newest commit instead, never older code over a newer result.
339
+ if (values.post && values["jobs-commit"] && values.at?.toLowerCase() === values["jobs-commit"].toLowerCase()) {
340
+ // Read from the branch itself, which moves at once: the pull request's head can still name the
341
+ // commit before the jobs' for a few seconds after their push.
342
+ const pr = await fetchPullRequest(ref);
343
+ const branch = pr.headRef
344
+ ? await api.get(`git/ref/heads/${pr.headRef.split("/").map(encodeURIComponent).join("/")}`).catch(() => null)
345
+ : null;
346
+ // Not told: no review, rather than one that may read older code than the newest.
347
+ if (!branch)
348
+ throw new Error(`Couldn't read ${pr.headRef ?? "the branch"} to tell whether the jobs' commit is still the newest. Run the review again.`);
349
+ const newest = branch.object.sha;
350
+ if (newest.toLowerCase() !== values.at.toLowerCase()) {
351
+ log(`The jobs' commit ${values.at.slice(0, 7)} isn't the newest any more, so this review reads ${newest.slice(0, 7)}.`);
352
+ values.at = newest;
353
+ }
354
+ }
355
+ // A comment that mentioned Mergelight started this run: the team's answer to the findings, for this review.
356
+ const answer = values.post ? teamAnswerFromEnv() : null;
357
+ if (answer) {
358
+ const pr = await fetchPullRequest(ref);
359
+ // A fork's pull request gets no review on a push, and a comment on one starts none either.
360
+ if (pr.headRepo && pr.headRepo.toLowerCase() !== `${ref.owner}/${ref.repo}`.toLowerCase()) {
361
+ log(`This pull request comes from the fork ${pr.headRepo}, so a comment on it starts no review.`);
362
+ return 0;
363
+ }
364
+ // Only someone who can push answers for the team. Not when GitHub can't say either.
365
+ if ((await askWriteAccess(api)(answer.by)) !== true) {
366
+ log(`${answer.by} can't push to this repository, or GitHub couldn't say, so their comment isn't the team's answer and starts no review.`);
367
+ return 0;
368
+ }
369
+ log(`Reading the answer ${answer.by} wrote${answer.url ? ` (${answer.url})` : ""}.`);
370
+ }
211
371
  let headSha = values.at ?? null;
212
372
  if (values.post) {
213
373
  headSha ??= (await fetchPullRequest(ref)).headSha;
214
- checkRunId = await startCheck(api, headSha, provider ?? "codex");
374
+ // A connect earlier in this run left its check going: the review carries it on, so no check stands
375
+ // finished in between, which a branch rule could take for a review that passed.
376
+ const handedOver = process.env.MERGELIGHT_PROVIDER ? Number(process.env.MERGELIGHT_CHECK_RUN) || undefined : undefined;
377
+ // The review's own check, as soon as it exists: the Action's last step finishes it if the review is
378
+ // cancelled first. Only in the Action, so another review later in a workflow never takes it for its
379
+ // own. The connect's check stays on the list too: the last step leaves it alone once it is finished,
380
+ // and finishes it when closing it here failed.
381
+ const record = (id) => {
382
+ if (process.env.MERGELIGHT_PROVIDER && process.env.GITHUB_ENV)
383
+ appendFileSync(process.env.GITHUB_ENV, `MERGELIGHT_CHECK_RUN=${[id, handedOver].filter(Boolean).join(" ")}\n`);
384
+ };
385
+ checkRunId = await startCheck(api, headSha, provider ?? "codex", handedOver, record);
215
386
  // Says which AI reviews from the start. The models' exact names follow once the first reviewer answers.
216
387
  // Without --provider the review runs on Codex, as reviewPullRequest decides.
217
388
  const firstGuess = values.model ?? (provider === "claude" ? "opus" : configuredModel());
218
- summaryComment = await startSummary(api, ref.number, { reviewer: { name: provider ?? "codex", model: firstGuess ?? null } }).catch((e) => {
389
+ summaryComment = await startSummary(api, ref.number, { reviewer: { name: provider ?? "codex", model: firstGuess ?? null } }, process.env.MERGELIGHT_PROMPT || undefined).catch((e) => {
219
390
  log(`Couldn't post the summary yet: ${e.message}`);
220
391
  return null;
221
392
  });
@@ -228,13 +399,23 @@ async function main() {
228
399
  let checksPosted = false;
229
400
  try {
230
401
  // The login step already found this login can't be refreshed, so don't send every reviewer to find out.
231
- if (process.env.MERGELIGHT_LOGIN_LOST === "1")
232
- throw new LoginError(loginFailureMessage(process.env.SECRET_NAME || undefined));
402
+ // Only when Codex is in this review: a Claude review whose Codex checker lost its login is checked by Claude.
403
+ const usesCodex = (provider ?? "codex") === "codex" || verifyWith === "codex";
404
+ if (usesCodex && process.env.MERGELIGHT_LOGIN_LOST === "1") {
405
+ const secret = process.env.SECRET_NAME || undefined;
406
+ // The login step says why when it held the login back on purpose, as for one other repositories share.
407
+ const note = process.env.MERGELIGHT_LOGIN_NOTE;
408
+ throw note ? new HeldLoginError(note) : new LoginError(loginFailureMessage(secret));
409
+ }
233
410
  // Before the threads are read: a reply written after this counts as newer than this review.
234
411
  const startedAt = new Date();
235
- let previous = values.post ? await previousFindings(api, ref.number, headSha ?? undefined) : undefined;
412
+ const earlier = values.post ? await previousReview(api, ref.number, headSha ?? undefined) : undefined;
413
+ let previous = earlier?.findings;
236
414
  const review = await reviewPullRequest(ref, {
237
415
  previous,
416
+ // The round this review becomes: from LATE_ROUND on, the loop breaker lets fewer findings hold the merge.
417
+ ...(earlier ? { round: earlier.round + 1 } : {}),
418
+ ...(answer ? { teamAnswer: { by: answer.by, text: answer.text } } : {}),
238
419
  memories: cloud.memories,
239
420
  rules: cloud.rules,
240
421
  rulesUnread: cloud.failed === true,
@@ -242,8 +423,10 @@ async function main() {
242
423
  writtenSkills: cloud.writtenSkills,
243
424
  checks: cloud.checks,
244
425
  onTeamChecks: (results) => (answered = results),
426
+ jobCommit,
245
427
  onModels: (models) => {
246
- naming = updatePendingSummary(api, summaryComment, models).catch((e) => {
428
+ // One after the other: a later name never lands before an earlier one, nor after the result.
429
+ naming = naming.then(() => updatePendingSummary(api, summaryComment, models)).catch((e) => {
247
430
  log(`Couldn't name the models yet: ${e.message}`);
248
431
  });
249
432
  },
@@ -258,6 +441,19 @@ async function main() {
258
441
  onProgress: progress.onProgress,
259
442
  });
260
443
  progress.stop();
444
+ if (verifyMissed && verifyMissed !== review.verifier?.name && !review.checker_missed) {
445
+ review.checker_missed = verifyMissed;
446
+ const why = values["verify-missed-why"];
447
+ if (why === "not-installed" || why === "login-failed")
448
+ review.checker_missed_why = why;
449
+ // Held back on purpose, as a login other repositories share: the login step's own words say why.
450
+ if (why === "held" && process.env.MERGELIGHT_LOGIN_NOTE) {
451
+ review.checker_missed_why = why;
452
+ review.checker_missed_note = process.env.MERGELIGHT_LOGIN_NOTE;
453
+ }
454
+ }
455
+ if (jobs)
456
+ review.jobs = { ...jobs, ...(jobs.commit ? { reviewed: review.pr.head_sha.toLowerCase() === jobs.commit.toLowerCase() } : {}) };
261
457
  const json = JSON.stringify(review, null, 2);
262
458
  if (values.out)
263
459
  writeFileSync(values.out, `${json}\n`);
@@ -268,6 +464,15 @@ async function main() {
268
464
  log(line);
269
465
  if (values.post) {
270
466
  previous = confirmReasons(previous, review.trace.rejected);
467
+ if (answer) {
468
+ // Mergelight answers the comment, and keeps each decision it took from it as a mark with the team's
469
+ // reason: the summary below counts them as handled, and later rounds and the agent tools read them.
470
+ const decided = decisionsFromAnswer(previous, review.trace.rejected);
471
+ await api.write("POST", `issues/${ref.number}/comments`, { body: answerReplyBody(answer, decided, review, review.pr.head_sha) }).catch((e) => log(`Couldn't answer the comment: ${e.message}`));
472
+ // Kept as the person's own decisions, so the server can remember their reasons for later pull requests.
473
+ previous = withDecisions(previous, decided, answer, review.pr.head_sha);
474
+ log(`Took ${decided.length} decision${decided.length === 1 ? "" : "s"} from the answer.`);
475
+ }
271
476
  // Reasons given in threads that this review sends to keep: the state holds them until the server confirms.
272
477
  // Also when the server couldn't be asked this time, so a waiting reason isn't dropped from the state.
273
478
  const remember = cloud.connected || cloud.failed ? (previous ?? []).filter((p) => p.handled?.from === "reply" && p.handled.remember && p.handled.at).map((p) => ({ id: p.id, at: p.handled.at, tries: (p.handled.tries ?? 0) + (cloud.connected ? 1 : 0) })) : [];
@@ -310,11 +515,13 @@ async function main() {
310
515
  if (values.post && headSha) {
311
516
  const login = err instanceof LoginError ? err : null;
312
517
  const limit = err instanceof LimitError ? err : null;
313
- const title = limit ? checkLimitTitle(limit.plan) : login ? checkLoginTitle(login.plan) : undefined;
314
- const notice = limit ? limitNotice(limit.plan, limit.resets) : login ? loginNotice(login.plan, message) : undefined;
315
- await failCheck(api, checkRunId, headSha, message, log, title).catch((e) => log(`Couldn't update the check: ${e.message}`));
518
+ // Held back on purpose is no login that failed: its own words say why.
519
+ const held = err instanceof HeldLoginError;
520
+ const title = limit ? checkLimitTitle(limit.plan) : held ? checkHeldTitle : login ? checkLoginTitle(login.plan) : undefined;
521
+ const notice = limit ? limitNotice(limit.plan, limit.resets) : held ? heldLoginNotice(message) : login ? loginNotice(login.plan, message) : undefined;
522
+ await failCheck(api, checkRunId, headSha, message, log, title, jobs).catch((e) => log(`Couldn't update the check: ${e.message}`));
316
523
  await naming;
317
- await failSummary(api, ref.number, notice).catch((e) => log(`Couldn't update the summary: ${e.message}`));
524
+ await failSummary(api, ref.number, notice, jobs).catch((e) => log(`Couldn't update the summary: ${e.message}`));
318
525
  // The newest commit wasn't reviewed. An approval Mergelight gave to an earlier commit must not count for this one.
319
526
  // With approvals turned off, none of Mergelight's approvals stands, this commit's included.
320
527
  await syncApproval(api, ref.number, "yellow", headSha, log, values["no-approve"] ? { why: APPROVALS_OFF } : { why: UNREVIEWED, otherCommitsOnly: true });
package/dist/cloud.js CHANGED
@@ -291,10 +291,11 @@ export async function fetchContext(deps = {}) {
291
291
  return { ...NOTHING, failed: true };
292
292
  }
293
293
  const answer = res.answer;
294
+ // Not on the dashboard: nothing of it, but whether the org's plan includes Jobs still counts.
294
295
  if (answer?.connected !== true)
295
- return NOTHING;
296
+ return { ...NOTHING, answered: true, ...(answer?.jobs === true ? { jobs: true } : {}) };
296
297
  const skills = Array.isArray(answer.skills) ? answer.skills.filter(isSkillPath).slice(0, 10) : [];
297
- return { connected: true, memories: readMemories(answer.memories), rules: readRules(answer.rules), skills, checks: readChecks(answer.checks), writtenSkills: readWrittenSkills(answer.written_skills) };
298
+ return { connected: true, answered: true, memories: readMemories(answer.memories), rules: readRules(answer.rules), skills, checks: readChecks(answer.checks), writtenSkills: readWrittenSkills(answer.written_skills), jobs: answer.jobs === true };
298
299
  }
299
300
  catch (err) {
300
301
  d.log(`Couldn't reach the Mergelight server (${err.message}). The review runs without it.`);
@@ -42,6 +42,11 @@ export function readPastedCode(body) {
42
42
  const text = body.trim();
43
43
  return /^[\w.~-]{10,500}#[\w.~-]{20,500}$/.test(text) ? text : null;
44
44
  }
45
+ /** How `script` runs the sign-in in a terminal of its own: Linux has util-linux's script, and macOS the BSD one, whose options differ. */
46
+ export function scriptArgs(platform = process.platform) {
47
+ const command = "stty cols 3000 rows 50; exec claude setup-token";
48
+ return platform === "darwin" || platform === "freebsd" ? ["-qF", "/dev/null", "sh", "-c", command] : ["-qfc", command, "/dev/null"];
49
+ }
45
50
  /**
46
51
  * Starts the sign-in. It needs a terminal, so `script` gives it one, wide enough that the link and the token
47
52
  * stay on one line. Nothing it prints is logged, because the token is in there. Null if no link appears.
@@ -53,7 +58,7 @@ export function startClaudeSignIn(spawnImpl = spawn, wait = { link: LINK_WAIT_MS
53
58
  let onOutput = () => { };
54
59
  let child;
55
60
  try {
56
- child = spawnImpl("script", ["-qfc", "stty cols 3000 rows 50; exec claude setup-token", "/dev/null"], { stdio: ["pipe", "pipe", "ignore"], env: { ...agentEnv(), TERM: "xterm-256color", BROWSER: "true" } });
61
+ child = spawnImpl("script", scriptArgs(), { stdio: ["pipe", "pipe", "ignore"], env: { ...agentEnv(), TERM: "xterm-256color", BROWSER: "true" } });
57
62
  }
58
63
  catch {
59
64
  resolve(null);
@@ -140,7 +145,14 @@ export async function waitForPastedCode(deps, timeoutMs = WAIT_MS, pollMs = POLL
140
145
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
141
146
  const end = now() + timeoutMs;
142
147
  while (now() < end && !deps.stopped?.()) {
143
- const code = readPastedCode((await deps.read().catch(() => null)) ?? "");
148
+ // A read GitHub never answers mustn't hold the wait past its end: the review waits for it.
149
+ let timer;
150
+ const late = new Promise((resolve) => {
151
+ timer = setTimeout(() => resolve(null), Math.max(0, end - now()));
152
+ });
153
+ const text = await Promise.race([deps.read().catch(() => null), late]);
154
+ clearTimeout(timer);
155
+ const code = readPastedCode(text ?? "");
144
156
  if (code)
145
157
  return code;
146
158
  await sleep(pollMs);
@@ -148,10 +160,11 @@ export async function waitForPastedCode(deps, timeoutMs = WAIT_MS, pollMs = POLL
148
160
  return null;
149
161
  }
150
162
  /** Hands the token to the rest of the job: hidden in its logs, and available to the steps that save and use it. */
151
- export function shareClaudeToken(token, env = process.env, print = console.log) {
163
+ export function shareClaudeToken(token, env = process.env, print = console.log, reviews = true) {
152
164
  if (!/^sk-ant-oat[\w-]+$/.test(token))
153
165
  throw new Error("That doesn't look like a Claude token.");
154
166
  print(`::add-mask::${token}`);
167
+ // A login connected to check the review leaves the reviewer as it is.
155
168
  if (env.GITHUB_ENV)
156
- appendFileSync(env.GITHUB_ENV, `MERGELIGHT_CLAUDE_TOKEN=${token}\nMERGELIGHT_PROVIDER=claude\nMERGELIGHT_CONNECT=0\n`);
169
+ appendFileSync(env.GITHUB_ENV, reviews ? `MERGELIGHT_CLAUDE_TOKEN=${token}\nMERGELIGHT_PROVIDER=claude\nMERGELIGHT_CONNECT=0\n` : `MERGELIGHT_CLAUDE_TOKEN=${token}\n`);
157
170
  }