@agentsdance/codejury 0.1.1 → 0.1.2

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/bin/jury.js CHANGED
@@ -56,7 +56,6 @@ Common flags
56
56
  --agents codex,grok only these reviewers (default: all installed)
57
57
  --judge codex one agent that triages and fixes (default: claude)
58
58
  --no-push fix locally, do not push
59
- --dry-run exercise the pipeline, spawn nothing
60
59
 
61
60
  Other commands
62
61
 
@@ -95,7 +94,9 @@ review (drives itself; no operator between rounds)
95
94
  --web open the console on this run (stays up when it ends)
96
95
  --port <n> console port, with --web (default 3080)
97
96
  --no-push commit fixes to the worktree without pushing
98
- --dry-run exercise the pipeline, spawn nothing
97
+ --dry-run (internal) exercise the pipeline, spawn no agents. Always
98
+ reports clean and triages nothing, so it says whether the
99
+ plumbing runs and never whether the code is good.
99
100
 
100
101
  review-once flags
101
102
  --dir <path> repo/worktree (default: cwd if Git, otherwise ~/.jury)
@@ -106,7 +107,6 @@ review-once flags
106
107
  --round <n> round number (default: next)
107
108
  --agents a,b only these reviewers (default: all enabled)
108
109
  --max-rounds <n> keep going until every reviewer approves, at most n (default 1)
109
- --dry-run do not spawn anything; exercise the pipeline
110
110
 
111
111
  web flags
112
112
  --dir <path> run-state root (default: cwd if Git, otherwise ~/.jury)
@@ -535,7 +535,7 @@ async function cmdAgent(argv) {
535
535
  values.push = values.push && !values["no-push"];
536
536
  const requestedWorktree = await commandDirectory(values.dir);
537
537
  const resolved = values.pr
538
- ? await resolvePrCheckout(values.pr, { allowPush: values.push })
538
+ ? await resolvePrCheckout(values.pr, { allowPush: values.push, dir: requestedWorktree })
539
539
  : null;
540
540
  const worktree = resolved?.worktree ?? requestedWorktree;
541
541
  resolvedCheckoutCleanup = resolved?.cleanup ?? null;
package/lib/repository.js CHANGED
@@ -5,8 +5,8 @@
5
5
  // PR's name. Keep this check independent of a hosting CLI so it also works for
6
6
  // self-hosted GitHub and GitLab instances.
7
7
  import { execFile } from "node:child_process";
8
- import { mkdtemp, rm } from "node:fs/promises";
9
- import { tmpdir } from "node:os";
8
+ import { mkdir, mkdtemp, rm } from "node:fs/promises";
9
+ import { homedir, tmpdir } from "node:os";
10
10
  import path from "node:path";
11
11
  import { promisify } from "node:util";
12
12
 
@@ -117,27 +117,222 @@ function branchAtHead(stdout, sha) {
117
117
 
118
118
  class MergeRequestCheckoutError extends Error {}
119
119
 
120
+ /**
121
+ * Fetch a merge request's head, falling back to numbered revision refs.
122
+ *
123
+ * Not every GitLab-compatible host publishes refs/merge-requests/<id>/head.
124
+ * Some expose the individual revisions instead, as
125
+ * refs/merge-requests/<id>/<id>/<revision>, where the highest revision is the
126
+ * current head. Returns the advertised sha when that fallback was used, so the
127
+ * caller can check the fetched commit against what the remote said: a request
128
+ * updated mid-fetch would otherwise be reviewed as though it were the head.
129
+ */
130
+ async function fetchMergeRequestHead(exec, worktree, number) {
131
+ const options = { cwd: worktree };
132
+ try {
133
+ await exec("git", ["fetch", "origin", `refs/merge-requests/${number}/head`], options);
134
+ return null;
135
+ } catch (err) {
136
+ // Only a genuinely absent ref justifies looking elsewhere. An auth or
137
+ // transport failure keeps its own error, or every network problem would be
138
+ // reported as an unusual ref layout.
139
+ if (!/couldn't find remote ref/i.test(String(err.stderr ?? "") + String(err.message))) throw err;
140
+ const prefix = `refs/merge-requests/${number}/${number}/`;
141
+ const { stdout } = await exec("git", ["ls-remote", "--refs", "origin", `${prefix}*`], options);
142
+ const revisions = String(stdout).split("\n").flatMap((line) => {
143
+ const [sha, ref] = line.trim().split(/\s+/);
144
+ if (!/^[a-f\d]{40,64}$/i.test(sha ?? "") || !ref?.startsWith(prefix)) return [];
145
+ const revision = ref.slice(prefix.length);
146
+ // Numeric, so revision 10 sorts above revision 9 rather than beside 1.
147
+ return /^[1-9]\d*$/.test(revision) ? [{ sha, ref, revision: BigInt(revision) }] : [];
148
+ });
149
+ revisions.sort((a, b) => (a.revision > b.revision ? -1 : a.revision < b.revision ? 1 : 0));
150
+ if (!revisions.length) throw err; // no revisions either: the original error is the true one
151
+ const latest = revisions[0];
152
+ await exec("git", ["fetch", "--quiet", "origin", latest.ref], options);
153
+ return latest.sha;
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Make origin/<trunk> resolvable in a clone taken from local disk. Best effort:
159
+ * offline the review may still fail, but it fails saying so rather than
160
+ * appearing to resolve and then diffing against a ref that is not there.
161
+ */
162
+ async function ensureTrunkRef(worktree, trunk, { exec }) {
163
+ try {
164
+ await exec("git", ["rev-parse", "--verify", `refs/remotes/origin/${trunk}^{commit}`], { cwd: worktree });
165
+ return;
166
+ } catch { /* not present: try to bring it in */ }
167
+ try {
168
+ await exec("git", ["fetch", "--quiet", "origin",
169
+ `refs/heads/${trunk}:refs/remotes/origin/${trunk}`], { cwd: worktree });
170
+ } catch { /* offline: leave it, the review reports the real failure */ }
171
+ }
172
+
173
+ /**
174
+ * Whether a repository already contains a specific commit — and is the
175
+ * repository the request actually names. The identity check is not optional:
176
+ * an unrelated checkout holding the same commit would be reviewed under this
177
+ * request's name.
178
+ */
179
+ async function hasCommit(dir, sha, { exec, target }) {
180
+ if (!dir || !sha || !await sameRepository(dir, target, { exec })) return false;
181
+ try {
182
+ await exec("git", ["-C", dir, "rev-parse", "--verify", `${sha}^{commit}`]);
183
+ return true;
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+
189
+ /**
190
+ * The commit a merge request points at, if this machine already has it.
191
+ *
192
+ * The head ref is the fragile part of resolving a merge request: GitLab prunes
193
+ * refs/merge-requests/<id>/head once a request is merged or old, so fetching it
194
+ * fails for requests that are otherwise perfectly reviewable. A repository that
195
+ * already contains the commits does not need that ref at all — and reviewing a
196
+ * branch you already have is the common case, not the exception.
197
+ *
198
+ * Read-only by construction: this resolves a revision and never checks anything
199
+ * out, because `jury <url>` run from master must not move the caller's tree.
200
+ */
201
+ /**
202
+ * Whether a directory is a checkout of the repository the URL names.
203
+ *
204
+ * The URL names one repository; a local checkout of a DIFFERENT one that
205
+ * happens to hold the same ref or commit would review unrelated code under this
206
+ * request's name. Every local shortcut passes through here first.
207
+ */
208
+ async function sameRepository(dir, target, { exec }) {
209
+ if (!dir || !target) return false;
210
+ try {
211
+ const { stdout } = await exec("git", ["-C", dir, "remote", "-v"]);
212
+ return String(stdout).split("\n").some((line) => {
213
+ const url = line.split(/\s+/)[1];
214
+ return url && repositoryFromRemote(url)?.display === target.display;
215
+ });
216
+ } catch {
217
+ return false; // not a repository, or no remotes: nothing to match against
218
+ }
219
+ }
220
+
221
+ async function localHead(dir, target, number, { exec, namespace, branch = null }) {
222
+ if (!dir || !await sameRepository(dir, target, { exec })) return null;
223
+
224
+ // Only the numbered ref. FETCH_HEAD was also consulted here, and it is not
225
+ // evidence of anything: it holds whatever the last fetch left behind, which
226
+ // after `git fetch origin main` is main. That resolved the wrong commit under
227
+ // this request's name, and — since branchAtHead then matched main on the
228
+ // remote — could make main the push target of a review that never examined it.
229
+ try {
230
+ const { stdout } = await exec(
231
+ "git", ["-C", dir, "rev-parse", "--verify", `${namespace}/${number}/head^{commit}`],
232
+ );
233
+ if (stdout.trim()) return stdout.trim();
234
+ } catch { /* an ordinary clone has no numbered ref; try the branch below */ }
235
+
236
+ // The numbered ref is the exception, not the rule: a normal clone or a
237
+ // source-branch checkout has none of them, only branches. Requiring it made
238
+ // this path unreachable for exactly the people the error told to "check out
239
+ // the source branch and pass --dir" — advice that could not work.
240
+ if (!branch) return null;
241
+ for (const rev of [`refs/remotes/origin/${branch}`, `refs/heads/${branch}`]) {
242
+ try {
243
+ const { stdout } = await exec("git", ["-C", dir, "rev-parse", "--verify", `${rev}^{commit}`]);
244
+ if (stdout.trim()) return stdout.trim();
245
+ } catch { /* try the next candidate */ }
246
+ }
247
+ return null;
248
+ }
249
+
120
250
  async function resolveMergeRequestCheckout(prUrl, target, number, {
121
- allowPush, exec, makeTemp, remove,
251
+ allowPush, exec, makeTemp, remove, dir, home = homedir(),
122
252
  }) {
123
- const worktree = await makeTemp(path.join(tmpdir(), `jury-mr-${number}-`));
253
+ // Where the clone lands when one is needed: the same ~/.jury the rest of the
254
+ // CLI already uses, rather than the system temp directory. The checkout is
255
+ // still removed when the review ends — this puts jury's working files under
256
+ // one predictable, inspectable root, and does not make them persist.
257
+ const worktree = await makeTemp(path.join(home, ".jury", "checkouts", `jury-mr-${number}-`));
258
+ let advertisedSha = null;
259
+ // Refresh the cached ref before trusting it. A ref fetched before the author
260
+ // pushed again names an obsolete head, and nothing about matching repository
261
+ // identity makes it current — a silent review of superseded code. When the
262
+ // refresh fails (offline, pruned) the cached ref is still better than nothing,
263
+ // which is the whole point of the local path.
264
+ if (dir && await sameRepository(dir, target, { exec })) {
265
+ try {
266
+ await exec("git", ["-C", dir, "fetch", "--quiet", "origin",
267
+ `refs/merge-requests/${number}/head:refs/merge-requests/${number}/head`, "--force"]);
268
+ } catch { /* keep whatever is cached */ }
269
+ }
270
+ const local = await localHead(dir, target, number, { exec, namespace: "refs/merge-requests" });
124
271
  try {
125
- await exec("git", ["clone", "--quiet", "--no-checkout", cloneUrlForMergeRequest(prUrl, target.path), worktree]);
126
- await exec("git", ["fetch", "--quiet", "origin", `refs/merge-requests/${number}/head`], { cwd: worktree });
127
- await exec("git", ["checkout", "--quiet", "-b", `jury-mr-${number}`, "FETCH_HEAD"], { cwd: worktree });
272
+ if (local) {
273
+ // The commits are already here. Clone from disk rather than the network:
274
+ // no credentials, no head ref, and nothing the host may have pruned.
275
+ await exec("git", ["clone", "--quiet", "--no-checkout", dir, worktree]);
276
+ await exec("git", ["checkout", "--quiet", "-b", `jury-mr-${number}`, local], { cwd: worktree });
277
+ // Cloning from disk points origin at a filesystem path. Left alone, the
278
+ // branch lookup below would read the local clone and pushTarget would
279
+ // push into it — a review that never reaches the real remote. Repoint
280
+ // origin at the repository the URL actually names.
281
+ await exec("git", ["remote", "set-url", "origin",
282
+ cloneUrlForMergeRequest(prUrl, target.path)], { cwd: worktree });
283
+ } else {
284
+ await exec("git", ["clone", "--quiet", "--no-checkout", cloneUrlForMergeRequest(prUrl, target.path), worktree]);
285
+ advertisedSha = await fetchMergeRequestHead(exec, worktree, number);
286
+ await exec("git", ["checkout", "--quiet", "-b", `jury-mr-${number}`, "FETCH_HEAD"], { cwd: worktree });
287
+ }
128
288
 
129
289
  const { stdout: actualOut } = await exec("git", ["rev-parse", "HEAD"], { cwd: worktree });
130
290
  const sha = actualOut.trim();
131
- const { stdout: trunkOut } = await exec(
132
- "git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: worktree },
133
- );
134
- const trunk = trunkOut.trim().replace(/^origin\//, "");
135
- if (!trunk) throw new MergeRequestCheckoutError(
291
+ if (advertisedSha && sha !== advertisedSha) {
292
+ throw new MergeRequestCheckoutError(
293
+ `merge request !${number} changed while it was being fetched; run the review again`,
294
+ );
295
+ }
296
+ // origin/HEAD comes from the clone SOURCE. Cloning the caller's repository
297
+ // copies whatever they had checked out, so a user sitting on the request's
298
+ // own source branch got that branch reported as trunk — and the review then
299
+ // diffed the branch against itself and saw nothing. Ask the real remote
300
+ // when the clone came from disk; fall back to the copied ref offline.
301
+ let trunk = "";
302
+ if (local) {
303
+ try {
304
+ const { stdout } = await exec("git", ["ls-remote", "--symref", "origin", "HEAD"], { cwd: worktree });
305
+ trunk = String(stdout).match(/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m)?.[1] ?? "";
306
+ } catch { /* offline: fall through to the local ref */ }
307
+ }
308
+ if (!trunk && !local) {
309
+ // Only for a network clone, where origin/HEAD came from the host. In a
310
+ // clone taken from disk it was copied from whatever the caller had
311
+ // checked out — often this request's own source branch, which would make
312
+ // the review diff the branch against itself and report an empty change.
313
+ const { stdout: trunkOut } = await exec(
314
+ "git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: worktree },
315
+ );
316
+ trunk = trunkOut.trim().replace(/^origin\//, "");
317
+ }
318
+ // A network clone with no default branch is a broken repository, and saying
319
+ // so is right. A local clone that simply could not reach the host is not:
320
+ // the CLI applies its own --trunk after this returns, so failing here would
321
+ // refuse a run the user had already told where trunk is. Leave it empty and
322
+ // let that flag win; the CLI reports a missing trunk itself if there is none.
323
+ if (!trunk && !local) throw new MergeRequestCheckoutError(
136
324
  `merge request !${number} repository has no default branch`,
137
325
  );
138
326
 
139
- const { stdout: headsOut } = await exec("git", ["ls-remote", "--heads", "origin"], { cwd: worktree });
140
- const branch = branchAtHead(headsOut, sha);
327
+ // Only when a push target is actually needed. This ran unconditionally, so
328
+ // a --no-push review with every commit already on disk still failed the
329
+ // moment the network was unreachable — the one case the local path exists
330
+ // to serve.
331
+ let branch = null;
332
+ if (allowPush) {
333
+ const { stdout: headsOut } = await exec("git", ["ls-remote", "--heads", "origin"], { cwd: worktree });
334
+ branch = branchAtHead(headsOut, sha);
335
+ }
141
336
  if (allowPush && !branch) {
142
337
  throw new MergeRequestCheckoutError(
143
338
  `resolved merge request !${number}, but its source branch is not uniquely available on origin — ` +
@@ -157,9 +352,18 @@ async function resolveMergeRequestCheckout(prUrl, target, number, {
157
352
  } catch (err) {
158
353
  await remove(worktree);
159
354
  if (err instanceof MergeRequestCheckoutError) throw err;
355
+ // git's own words, not a guess. --quiet used to hide them and only the
356
+ // first line survived, so a pruned head ref — the usual cause — was
357
+ // reported as a probable authentication problem. Whatever git said is the
358
+ // one thing that distinguishes the cases.
359
+ const said = [err.stderr, err.message].map((t) => String(t ?? "").trim()).find(Boolean) ?? "";
360
+ const missingRef = /couldn't find remote ref|no matching remote head/i.test(said);
160
361
  throw new Error(
161
- `could not resolve ${target.display} merge request !${number}: ${String(err.message).split("\n")[0]} — ` +
162
- "check Git authentication and refs/merge-requests support, or check out the source branch and pass --dir",
362
+ `could not resolve ${target.display} merge request !${number}: ${said.split("\n")[0]} — ` +
363
+ (missingRef
364
+ ? `${target.host} has no refs/merge-requests/${number}/head; hosts prune it once a request ` +
365
+ "is merged or old. Check out the source branch and pass --dir."
366
+ : "check Git authentication and refs/merge-requests support, or check out the source branch and pass --dir"),
163
367
  );
164
368
  }
165
369
  }
@@ -185,15 +389,24 @@ function remoteForRepository(origin, repoPath) {
185
389
  export async function resolvePrCheckout(prUrl, {
186
390
  allowPush = true,
187
391
  exec = run,
188
- makeTemp = mkdtemp,
392
+ // Creates the parent too: a checkout under ~/.jury has a directory that may
393
+ // not exist yet, and a caller that injects this must not need the real one.
394
+ makeTemp = async (prefix) => {
395
+ await mkdir(path.dirname(prefix), { recursive: true });
396
+ return mkdtemp(prefix);
397
+ },
189
398
  remove = (dir) => rm(dir, { recursive: true, force: true }),
399
+ // The caller's checkout, when it has one. Consulted before the network: a
400
+ // repository that already holds the request's commits needs no head ref.
401
+ dir = null,
402
+ home = homedir(),
190
403
  } = {}) {
191
404
  const target = repositoryFromPrUrl(prUrl);
192
405
  const number = githubNumber(prUrl);
193
406
  const mrNumber = mergeRequestNumber(prUrl);
194
407
  if (target && mrNumber) {
195
408
  return resolveMergeRequestCheckout(prUrl, target, mrNumber, {
196
- allowPush, exec, makeTemp, remove,
409
+ allowPush, exec, makeTemp, remove, dir, home,
197
410
  });
198
411
  }
199
412
  if (!target || !number) {
@@ -229,11 +442,33 @@ export async function resolvePrCheckout(prUrl, {
229
442
  );
230
443
  }
231
444
 
232
- const worktree = await makeTemp(path.join(tmpdir(), `jury-pr-${number}-`));
445
+ const worktree = await makeTemp(path.join(home, ".jury", "checkouts", `jury-pr-${number}-`));
446
+ // `gh` already gave the authoritative head oid, so that — not a cached ref —
447
+ // is what to look for locally. Consulting refs/pull/<id>/head first checked
448
+ // out whatever it pointed at when it was last fetched, which then failed the
449
+ // assertion below: a stale ref blocked a review whose real head was sitting
450
+ // in the same repository.
451
+ // `gh` gives both the oid and the branch name, so a plain checkout of the PR
452
+ // branch resolves here without any refs/pull ref existing.
453
+ const local = dir && await hasCommit(dir, details.headRefOid, { exec, target })
454
+ ? details.headRefOid
455
+ : await localHead(dir, target, number, {
456
+ exec, namespace: "refs/pull", branch: details.headRefName,
457
+ });
233
458
  try {
234
- await exec("gh", ["repo", "clone", target.display, worktree, "--", "--quiet"]);
235
- await exec("git", ["fetch", "--quiet", "origin", `refs/pull/${number}/head`], { cwd: worktree });
236
- await exec("git", ["checkout", "--quiet", "-b", `jury-pr-${number}`, "FETCH_HEAD"], { cwd: worktree });
459
+ if (local) {
460
+ await exec("git", ["clone", "--quiet", "--no-checkout", dir, worktree]);
461
+ await exec("git", ["checkout", "--quiet", "-b", `jury-pr-${number}`, local], { cwd: worktree });
462
+ await exec("git", ["remote", "set-url", "origin", cloneUrlForMergeRequest(prUrl, target.path)],
463
+ { cwd: worktree });
464
+ // Same as the merge request path: a clone of a developer's checkout has
465
+ // their local branches, not origin/<base>, and every review prompt needs it.
466
+ await ensureTrunkRef(worktree, details.baseRefName, { exec });
467
+ } else {
468
+ await exec("gh", ["repo", "clone", target.display, worktree, "--", "--quiet"]);
469
+ await exec("git", ["fetch", "origin", `refs/pull/${number}/head`], { cwd: worktree });
470
+ await exec("git", ["checkout", "--quiet", "-b", `jury-pr-${number}`, "FETCH_HEAD"], { cwd: worktree });
471
+ }
237
472
 
238
473
  const { stdout: actual } = await exec("git", ["rev-parse", "HEAD"], { cwd: worktree });
239
474
  if (actual.trim() !== details.headRefOid) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsdance/codejury",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Independent AI reviewers that iterate until your pull request is clean.",
5
5
  "keywords": [
6
6
  "code-review",