@mergelight/cli 0.1.17 → 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/review.js CHANGED
@@ -4,11 +4,14 @@ import { join } from "node:path";
4
4
  import { actionsUsedBy, fetchActionSources, notRead } from "./action-source.js";
5
5
  import { fetchPullRequest } from "./github.js";
6
6
  import { buildCheckPrompt, buildHunterPrompt, buildSweepPrompt, buildVerifierPrompt, focusesFor, ruleApplies, usedMemories, } from "./prompt.js";
7
- import { LimitError, LoginError } from "./providers/codex.js";
8
- import { claudeAvailable, runModel, TOOLING } from "./providers/index.js";
7
+ import { LimitError, LoginError, SandboxError } from "./providers/codex.js";
8
+ import { MAX_REPO_RULES } from "./repo-rules.js";
9
+ import { claudeAvailable, runModel as runOneModel, TOOLING } from "./providers/index.js";
9
10
  import { candidateSchema, checkSchema, reviewSchema, reviewSchemaWithDecisions } from "./schema.js";
10
11
  import { CHECK_TIMEOUT_MS, startTeamChecks } from "./checks.js";
11
12
  import { run } from "./run.js";
13
+ import { LATE_ROUND } from "./types.js";
14
+ export { LATE_ROUND } from "./types.js";
12
15
  import { cacheDir, prepareWorkspace } from "./workspace.js";
13
16
  /**
14
17
  * Stable id for a finding: the file plus the code it points at, ignoring
@@ -63,19 +66,33 @@ export function assignIds(findings, previous, fingerprintOf) {
63
66
  * Posting everything it would fix meant about 4.5 comments per PR, and all of
64
67
  * Codex's about 6.
65
68
  */
66
- export function tierOf(f) {
67
- // Teams fixed few of these: 19% of minor risks and 10% of rare findings, against 45% of minor bugs. They stay
68
- // readable in the collapsed section, and a major bug is never hidden, because it decides the red light.
69
+ export function tierOf(f, round = 1) {
70
+ return placeFinding(f, round).tier;
71
+ }
72
+ /** A major bug, or a major problem that exposes secrets, data or actions: it holds the merge in every round. */
73
+ export function mustHold(f) {
74
+ return f.severity === "major" && (f.class === "bug" || f.security === true);
75
+ }
76
+ /**
77
+ * Where a finding goes in this round, and why the loop breaker left it alone when it would otherwise
78
+ * hold the merge. Teams fixed few rare findings (10%, against 45% of minor bugs), and only a problem
79
+ * known to break for real users is worth another round.
80
+ */
81
+ export function placeFinding(f, round = 1) {
82
+ // Teams fixed few minor risks (19%). They stay readable in the collapsed section.
69
83
  const majorBug = f.class === "bug" && f.severity !== "minor";
70
- if (!majorBug && ((f.class === "risk" && f.severity === "minor") || f.likelihood === "rare"))
71
- return "hardening";
72
- if (f.rank)
73
- return "post";
74
- if (f.recommendation === "fix")
75
- return "list";
76
- if (f.recommendation === "decide")
77
- return "decision";
78
- return "hardening";
84
+ const tier = !majorBug && f.class === "risk" && f.severity === "minor" ? "hardening" : f.rank ? "post" : f.recommendation === "fix" ? "list" : f.recommendation === "decide" ? "decision" : "hardening";
85
+ // A major bug or a major security problem holds the merge even when the verifier said to leave it,
86
+ // as for a costly fix: a person decides.
87
+ if (mustHold(f))
88
+ return { tier: tier === "hardening" ? "decision" : tier };
89
+ if (tier === "hardening")
90
+ return { tier };
91
+ if (f.likelihood === "rare" || f.likelihood === "theoretical")
92
+ return { tier: "hardening", left_alone: "rare" };
93
+ if (round >= LATE_ROUND && f.likelihood !== "common")
94
+ return { tier: "hardening", left_alone: "late" };
95
+ return { tier };
79
96
  }
80
97
  /** Red if a major bug must be fixed, yellow if anything else is posted or needs a decision, green otherwise. */
81
98
  export function mergeLight(findings) {
@@ -98,6 +115,14 @@ const ORDER = { bug: 0, risk: 1, hardening: 2 };
98
115
  * low) found 41 of 51 fixed problems at high, 32 at medium and 29 at low.
99
116
  */
100
117
  export const DEFAULT_EFFORT = "high";
118
+ function counting(tally) {
119
+ return (provider, opts) => runOneModel(provider, opts).then((r) => {
120
+ tally.input += r.usage?.input_tokens ?? 0;
121
+ tally.cached += r.usage?.cached_input_tokens ?? 0;
122
+ tally.output += r.usage?.output_tokens ?? 0;
123
+ return r;
124
+ });
125
+ }
101
126
  /** Tells the prompts which tools the agent has. Without a shell it can't run git diff, so a big diff goes into the checkout. */
102
127
  function forProvider(dir, input, provider) {
103
128
  const tooling = TOOLING[provider];
@@ -127,7 +152,7 @@ async function checkDiff(dir, base, head, files) {
127
152
  * same candidates through another model.
128
153
  */
129
154
  export async function verifyCandidates(dir, input, found, opts) {
130
- const result = await runModel(opts.provider, {
155
+ const result = await runOneModel(opts.provider, {
131
156
  cwd: dir,
132
157
  prompt: buildVerifierPrompt(forProvider(dir, input, opts.provider), found),
133
158
  // Only a verifier that was given the team's earlier decisions is asked which one it used.
@@ -142,13 +167,14 @@ export async function verifyCandidates(dir, input, found, opts) {
142
167
  const findings = assignIds(review.findings, input.previous ?? [], (f) => fingerprint(dir, f))
143
168
  .map((f, i) => {
144
169
  const rank = top.includes(i + 1) ? top.indexOf(i + 1) + 1 : null;
145
- return { ...f, tier: tierOf({ ...f, rank }), rank };
170
+ const { tier, left_alone } = placeFinding({ ...f, rank }, opts.round);
171
+ return { ...f, tier, rank, ...(left_alone ? { left_alone } : {}) };
146
172
  })
147
173
  .sort((a, b) => ORDER[a.class] - ORDER[b.class] || a.file.localeCompare(b.file) || a.line - b.line);
148
- return { summary: review.summary, findings, rejected: review.rejected, model: result.model, cost_usd: result.cost_usd ?? null };
174
+ return { summary: review.summary, findings, rejected: review.rejected, model: result.model, cost_usd: result.cost_usd ?? null, usage: result.usage };
149
175
  }
150
- /** Every rule a team can have for one repository: 50 for the org and 50 of its own. None is dropped. */
151
- const MAX_RULES = 100;
176
+ /** Every rule a team can have for one repository: 50 for the org and 50 of its own on the dashboard, and those in its rule files. None is dropped. */
177
+ const MAX_RULES = 100 + MAX_REPO_RULES;
152
178
  /** The summary, with what the reader must know about the team's rules: a guarded file was changed, or the rules couldn't be read. */
153
179
  export function summaryWith(summary, needsHuman, rulesUnread) {
154
180
  // As code, so a name like __init__.py shows as it is and not as bold text.
@@ -189,6 +215,8 @@ export function memoriesFor(memories, changedFiles, pullRequest) {
189
215
  export async function reviewPullRequest(ref, opts = {}) {
190
216
  const started = Date.now();
191
217
  const progress = opts.onProgress ?? (() => { });
218
+ const tokens = { input: 0, cached: 0, output: 0 };
219
+ const runModel = counting(tokens);
192
220
  const effort = opts.effort ?? DEFAULT_EFFORT;
193
221
  const provider = opts.provider ?? "codex";
194
222
  const hunterModel = provider === "claude" ? (opts.model ?? "opus") : opts.model;
@@ -204,6 +232,15 @@ export async function reviewPullRequest(ref, opts = {}) {
204
232
  progress(`Using your team's skill${teamSkills.length === 1 ? "" : "s"}: ${teamSkills.map((s) => s.name).join(", ")}`);
205
233
  if (ws.conventions.length)
206
234
  progress(`Using ${ws.conventions.map((c) => c.path).join(", ")} from ${pr.baseRef}`);
235
+ const ruleFiles = [...new Set(ws.rules.filter((r) => ruleApplies(r, ws.touchedPaths)).map((r) => r.source))];
236
+ if (ruleFiles.length)
237
+ progress(`Using the rules in ${ruleFiles.join(", ")} from ${pr.baseRef}`);
238
+ if (ws.teamFilesLate)
239
+ progress(`Couldn't read the repository's instruction and rule files from ${pr.baseRef} in time, so this review runs without them`);
240
+ if (ws.droppedRules)
241
+ progress(`Left out ${ws.droppedRules} of the repository's rules for this change: over the limit of ${MAX_REPO_RULES} rules or 30,000 characters`);
242
+ if (ws.unreadRules.length)
243
+ progress(`Found no rules to use in ${ws.unreadRules.slice(0, 10).join(", ")}${ws.unreadRules.length > 10 ? ` and ${ws.unreadRules.length - 10} more` : ""}: empty, too large, a link out of the repository, a Copilot file without applyTo or kept out of code review, past the limit of 100 rule files, or unreadable`);
207
244
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
208
245
  const log = (step) => join(cacheDir(), "logs", `${pr.owner}-${pr.repo}-${pr.number}-${stamp}-${step}.log`);
209
246
  let checksRun = null;
@@ -216,11 +253,15 @@ export async function reviewPullRequest(ref, opts = {}) {
216
253
  diff: ws.diff,
217
254
  diffTruncated: ws.diffTruncated,
218
255
  previous: opts.previous,
256
+ ...(opts.round ? { round: opts.round } : {}),
219
257
  memories: memoriesFor(opts.memories, ws.changedFiles.map((f) => f.path), pr.number),
220
258
  // Matched against every path the pull request touches, exactly as git has it.
221
259
  skills: teamSkills,
222
260
  conventions: ws.conventions,
223
- rules: (opts.rules ?? []).filter((r) => r.kind === "rule" && ruleApplies(r, ws.touchedPaths)).slice(0, MAX_RULES),
261
+ // Only when it is the commit under review: an older job commit is part of the diff like any other.
262
+ ...(opts.jobCommit && opts.jobCommit.sha === ws.headSha ? { jobCommit: opts.jobCommit } : {}),
263
+ // The dashboard's rules, then the ones written in the repository.
264
+ rules: [...(opts.rules ?? []), ...ws.rules].filter((r) => r.kind === "rule" && ruleApplies(r, ws.touchedPaths)).slice(0, MAX_RULES),
224
265
  };
225
266
  // Step 1: hunters, one per area, in parallel. One failing doesn't sink the review.
226
267
  const addedTo = ws.changedFiles.filter((f) => f.added > 0).map((f) => f.path);
@@ -233,6 +274,23 @@ export async function reviewPullRequest(ref, opts = {}) {
233
274
  input.actionSources = await fetchActionSources(uses);
234
275
  unread = notRead(input.actionSources);
235
276
  }
277
+ // Who checks is known before the hunt, so the first reviewer that answers can name both models.
278
+ const verifyWith = opts.verifyWith ?? (provider === "claude" || (await claudeAvailable()) ? "claude" : "codex");
279
+ // The reviewer's model only carries over to the same AI: a Claude model name means nothing to Codex.
280
+ const verifyModel = verifyWith === "codex" ? (opts.verifyModel ?? (provider === "codex" ? opts.model : undefined)) : (opts.verifyModel ?? "opus");
281
+ let named = false;
282
+ const nameModels = (reviewerModel) => {
283
+ if (named)
284
+ return;
285
+ named = true;
286
+ // The same tool with no model of its own, or an alias of the one that answered ("opus" for
287
+ // "claude-opus-5-5"), is the same model: the comment mustn't say a second one checks.
288
+ const sameModel = verifyWith === provider && (!verifyModel || verifyModel === reviewerModel || (!/\d/.test(verifyModel) && (reviewerModel ?? "").includes(verifyModel)));
289
+ opts.onModels?.({
290
+ reviewer: { name: provider, model: reviewerModel },
291
+ checker: { name: verifyWith, model: sameModel ? reviewerModel : (verifyModel ?? null) },
292
+ });
293
+ };
236
294
  let done = 0;
237
295
  progress(`Hunting for problems (0 of ${focuses.length} areas done)`);
238
296
  const hunts = await Promise.allSettled(focuses.map(async (focus) => {
@@ -245,6 +303,7 @@ export async function reviewPullRequest(ref, opts = {}) {
245
303
  logFile: log(`hunt-${focus}`),
246
304
  });
247
305
  done++;
306
+ nameModels(result.model ?? hunterModel ?? null);
248
307
  progress(`Hunting for problems (${done} of ${focuses.length} areas done)`);
249
308
  return { focus, candidates: result.output.candidates, model: result.model };
250
309
  }));
@@ -301,20 +360,45 @@ export async function reviewPullRequest(ref, opts = {}) {
301
360
  checksRun = teamChecks;
302
361
  // Step 2: the verifier tries to disprove each candidate and sorts the rest.
303
362
  // Opus checks better than Codex: in the eval it posted a third less and kept the same finds.
304
- const verifyWith = opts.verifyWith ?? (provider === "claude" || (await claudeAvailable()) ? "claude" : "codex");
305
363
  if (!opts.verifyWith && verifyWith === "codex")
306
364
  progress("Claude Code isn't installed, so Codex checks the findings");
307
365
  progress(`Checking ${found.length} candidate${found.length === 1 ? "" : "s"}${verifyWith === "codex" ? "" : ` with ${verifyWith}`}`);
308
- const verified = await verifyCandidates(ws.dir, input, found, {
309
- provider: verifyWith,
310
- model: verifyWith === "codex" ? (opts.verifyModel ?? opts.model) : (opts.verifyModel ?? "opus"),
366
+ const servedModelSoFar = () => {
367
+ const first = hunts.find((h) => h.status === "fulfilled");
368
+ return first?.status === "fulfilled" ? first.value.model : null;
369
+ };
370
+ const verifyWithAi = (ai, model) => verifyCandidates(ws.dir, input, found, {
371
+ provider: ai,
372
+ round: opts.round,
373
+ model,
311
374
  effort,
312
- logFile: log("verify"),
375
+ logFile: log(ai === verifyWith ? "verify" : "verify-fallback"),
313
376
  onCommand: (cmd) => progress(`Checking ${found.length} candidates: ${cmd.replace(/\s+/g, " ").slice(0, 80)}`, true),
314
377
  });
378
+ // The other AI checking is extra: when its login doesn't work or its plan is used up, the reviewer's
379
+ // own AI checks instead, and the summary says why. The reviewer's own failures still stop the review.
380
+ let checkerFailed;
381
+ let verified;
382
+ try {
383
+ verified = await verifyWithAi(verifyWith, verifyModel);
384
+ }
385
+ catch (err) {
386
+ if (verifyWith === provider || !(err instanceof LoginError || err instanceof LimitError || err instanceof SandboxError))
387
+ throw err;
388
+ checkerFailed = err instanceof LimitError ? "limit" : err instanceof SandboxError ? "sandbox" : "login-failed";
389
+ progress(`${verifyWith === "codex" ? "Codex" : "Claude"} couldn't check (${err.message.slice(0, 120)}), so ${provider === "codex" ? "Codex" : "Claude"} checks the findings`);
390
+ const fallbackModel = provider === "codex" ? opts.model : (opts.model ?? "opus");
391
+ // The live comment names the AI that checks now.
392
+ opts.onModels?.({ reviewer: { name: provider, model: servedModelSoFar() }, checker: { name: provider, model: fallbackModel ?? null } });
393
+ verified = await verifyWithAi(provider, fallbackModel);
394
+ }
395
+ const checkedBy = checkerFailed ? provider : verifyWith;
315
396
  // Every path the pull request touches counts here, the lockfiles and generated files the reviewers skip included.
316
397
  const needsHuman = filesNeedingHuman(opts.rules, ws.touchedPaths);
317
398
  const team_checks = teamChecks ? await teamChecks.done : null;
399
+ tokens.input += verified.usage?.input_tokens ?? 0;
400
+ tokens.cached += verified.usage?.cached_input_tokens ?? 0;
401
+ tokens.output += verified.usage?.output_tokens ?? 0;
318
402
  const firstHunt = hunts.find((h) => h.status === "fulfilled");
319
403
  const servedModel = firstHunt?.status === "fulfilled" ? firstHunt.value.model : null;
320
404
  return {
@@ -329,7 +413,8 @@ export async function reviewPullRequest(ref, opts = {}) {
329
413
  head_sha: ws.headSha,
330
414
  },
331
415
  provider: { name: provider, model: servedModel, effort },
332
- verifier: { name: verifyWith, model: verified.model, effort, cost_usd: verified.cost_usd },
416
+ verifier: { name: checkedBy, model: verified.model, effort, cost_usd: verified.cost_usd },
417
+ ...(checkerFailed ? { checker_missed: verifyWith, checker_missed_why: checkerFailed } : {}),
333
418
  light: lightWith(verified.findings, needsHuman),
334
419
  summary: summaryWith(verified.summary, needsHuman, opts.rulesUnread === true),
335
420
  ...(needsHuman.length ? { needs_human: needsHuman } : {}),
@@ -343,6 +428,7 @@ export async function reviewPullRequest(ref, opts = {}) {
343
428
  files_changed: pr.changedFiles,
344
429
  additions: pr.additions,
345
430
  deletions: pr.deletions,
431
+ tokens: { ...tokens },
346
432
  },
347
433
  trace: {
348
434
  candidates: found,