@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/workspace.js CHANGED
@@ -1,8 +1,10 @@
1
- import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs";
1
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, renameSync, rmSync, statSync } from "node:fs";
2
2
  import { homedir, tmpdir } from "node:os";
3
3
  import { join, posix } from "node:path";
4
4
  import { run, runOk } from "./run.js";
5
5
  import { importSkills, SKILL_GIT_TIMEOUT_MS, SKILL_IMPORT_TIMEOUT_MS, writeSkills } from "./skills.js";
6
+ import { folded, guardedFolders, JOB_FILE, MAX_JOB_FILES, readJobs, refusedPath } from "./jobs.js";
7
+ import { parseRuleFile, repoRules, RULE_FILE } from "./repo-rules.js";
6
8
  /** Lockfiles and generated files are left out of the diff the model sees. */
7
9
  const EXCLUDES = [
8
10
  "package-lock.json",
@@ -74,7 +76,7 @@ export function removeAgentSkills(checkout) {
74
76
  * contents of its own, so reading a skill the pull request changed asks GitHub for it: with the
75
77
  * same login as every other git call here, never with a prompt, and never for long.
76
78
  */
77
- async function skillsFor(mirror, base, checkout, folders) {
79
+ export async function skillsFor(mirror, base, checkout, folders) {
78
80
  if (!folders.length)
79
81
  return [];
80
82
  const gitInMirror = (args) => run("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "-C", mirror, ...args], {
@@ -103,8 +105,9 @@ export const MAX_CONVENTIONS_CHARS = 40_000;
103
105
  export const MAX_CONVENTION_FILES = 12;
104
106
  /** A file larger than this isn't read at all. */
105
107
  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. */
108
+ /** Which instruction files apply: the root ones, and AGENTS.md or CLAUDE.md in a folder above a changed file. */
107
109
  export function conventionPaths(all, changedPaths) {
110
+ // .github/instructions files are rules now (repo-rules.ts), not background.
108
111
  const folders = new Set();
109
112
  for (const changed of changedPaths) {
110
113
  const parts = changed.split("/").slice(0, -1);
@@ -113,7 +116,6 @@ export function conventionPaths(all, changedPaths) {
113
116
  }
114
117
  const present = new Set(all);
115
118
  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
119
  const nested = all
118
120
  .filter((p) => {
119
121
  const at = p.lastIndexOf("/");
@@ -121,8 +123,7 @@ export function conventionPaths(all, changedPaths) {
121
123
  })
122
124
  // Closest to the root first: a folder's file comes before the ones in its subfolders.
123
125
  .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
+ return [...root, ...nested];
126
127
  }
127
128
  /**
128
129
  * The team's instruction files as the base branch has them. The checkout is the pull request's, and
@@ -131,42 +132,450 @@ export function conventionPaths(all, changedPaths) {
131
132
  * read in time is left out: it never stops a review.
132
133
  */
133
134
  export async function conventionsFor(mirror, base, changedPaths = []) {
135
+ return (await teamFilesFor(mirror, base, changedPaths)).conventions;
136
+ }
137
+ /** A git read that failed this time, told apart from a file that is too large or missing. */
138
+ const FAILED = Symbol("failed");
139
+ /**
140
+ * The base branch's files, listed once, and a way to read one. A file that is a link is followed once,
141
+ * to a file inside the repository. A file that is missing, too large or can't be read is null. Null as a
142
+ * whole when the branch can't be listed.
143
+ */
144
+ async function baseTree(mirror, base) {
134
145
  const git = (args) => run("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "-C", mirror, ...args], {
135
146
  env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
136
147
  timeoutMs: SKILL_GIT_TIMEOUT_MS,
137
148
  }).catch(() => null);
138
149
  const listed = await git(["ls-tree", "-r", "-z", "--full-tree", base]);
139
150
  if (listed?.code !== 0)
140
- return [];
151
+ return null;
141
152
  const tree = new Map();
142
153
  for (const entry of listed.stdout.split("\0")) {
143
154
  const m = /^(\d{6}) blob ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(entry);
144
155
  if (m)
145
156
  tree.set(m[3], { mode: m[1], sha: m[2] });
146
157
  }
147
- const blob = async (sha) => {
158
+ /** A file's text, null when it is too large, or FAILED when git couldn't read it this time. */
159
+ const blob = async (sha, max = MAX_CONVENTION_BYTES) => {
148
160
  const sized = await git(["cat-file", "-s", sha]);
149
- if (sized?.code !== 0 || !(Number(sized.stdout.trim()) <= MAX_CONVENTION_BYTES))
161
+ if (sized?.code !== 0)
162
+ return FAILED;
163
+ if (!(Number(sized.stdout.trim()) <= max))
150
164
  return null;
151
165
  const read = await git(["cat-file", "blob", sha]);
152
- return read?.code === 0 ? read.stdout : null;
166
+ return read?.code === 0 ? read.stdout : FAILED;
153
167
  };
154
- const read = async (path) => {
168
+ /** What a link holds, as git keeps it: its target, as written. Null for no link, "unread" when git couldn't read it this time. Read once each. */
169
+ const links = new Map();
170
+ const linkContent = (path) => {
171
+ const known = links.get(path);
172
+ if (known)
173
+ return known;
174
+ const file = tree.get(path);
175
+ const read = file?.mode !== "120000" ? Promise.resolve(null) : blob(file.sha).then((content) => (content === FAILED || content === null ? "unread" : content));
176
+ links.set(path, read);
177
+ return read;
178
+ };
179
+ /** A file, null when there is none to read, or FAILED when git couldn't read it this time. */
180
+ const readOrFail = async (path, max = MAX_CONVENTION_BYTES) => {
155
181
  let file = tree.get(path);
156
- if (file?.mode === "120000") {
182
+ const link = file?.mode === "120000";
183
+ let resolved;
184
+ if (file && link) {
157
185
  // 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));
186
+ const content = await blob(file.sha);
187
+ if (content === FAILED)
188
+ return FAILED;
189
+ const target = content?.trim() ?? "";
190
+ resolved = posix.normalize(posix.join(posix.dirname(path), target));
160
191
  if (!target || target.startsWith("/") || resolved === ".." || resolved.startsWith("../"))
161
192
  return null;
162
193
  file = tree.get(resolved);
163
194
  }
164
195
  if (!file || (file.mode !== "100644" && file.mode !== "100755"))
165
196
  return null;
166
- const text = (await blob(file.sha))?.trim();
167
- return text ? { path, sha: file.sha, text } : null;
197
+ const content = await blob(file.sha, max);
198
+ if (content === FAILED)
199
+ return FAILED;
200
+ const text = content?.trim();
201
+ return text ? { path, sha: file.sha, text, link, ...(resolved ? { target: resolved } : {}) } : null;
202
+ };
203
+ const read = async (path) => {
204
+ const file = await readOrFail(path);
205
+ return file === FAILED ? null : file;
168
206
  };
169
- const found = await Promise.all(conventionPaths([...tree.keys()], changedPaths).slice(0, MAX_CONVENTION_FILES * 2).map(read));
207
+ /** A file's size in bytes, or null when git can't say. */
208
+ const size = async (path) => {
209
+ const file = tree.get(path);
210
+ const sized = file ? await git(["cat-file", "-s", file.sha]) : null;
211
+ return sized?.code === 0 ? Number(sized.stdout.trim()) : null;
212
+ };
213
+ return { paths: [...tree.keys()], mode: (path) => tree.get(path)?.mode, read, readOrFail, linkContent, size };
214
+ }
215
+ /**
216
+ * The repository's jobs, as the base branch has them, and every job file that was left out with the
217
+ * reason. A pull request can't add a job or widen one for itself: its own copies don't count.
218
+ */
219
+ export async function jobFilesFor(mirror, base, guardFor) {
220
+ const tree = await baseTree(mirror, base);
221
+ if (!tree)
222
+ return { jobs: [], problems: [], guarded: [], incomplete: "The base branch couldn't be read this time, so no job runs. The next push tries again." };
223
+ const problems = [];
224
+ // A file that looks meant as a job but sits deeper or ends in .MD is named, never skipped without a word.
225
+ for (const p of tree.paths) {
226
+ // A README or a .gitkeep explains or keeps the folder: neither is a job. A README written like a job is named.
227
+ if (/^\.mergelight\/jobs\/(?:readme\.md|\.gitkeep)$/i.test(p)) {
228
+ if (/readme\.md$/i.test(p) && (await tree.read(p))?.text.startsWith("---"))
229
+ problems.push({ source: p, problem: "is the folder's notes, never read as a job: give the job a file name of its own" });
230
+ continue;
231
+ }
232
+ if (p.toLowerCase().startsWith(".mergelight/jobs/") && !JOB_FILE.test(p))
233
+ problems.push({ source: p, problem: "isn't read: a job file sits right in .mergelight/jobs and ends in .md" });
234
+ // A link in place of the folder, or a file next to it, holds no job either.
235
+ else if (/^\.mergelight(?:\/jobs)?$/i.test(p) || p.toLowerCase().startsWith(".mergelight/jobs."))
236
+ problems.push({ source: p, problem: "isn't read: jobs are files right in the .mergelight/jobs folder, which can't be a link" });
237
+ }
238
+ const all = tree.paths.filter((p) => JOB_FILE.test(p) && !/\/readme\.md$/i.test(p)).sort();
239
+ const tries = await Promise.all(all.slice(0, MAX_JOB_FILES).map((p) => tree.readOrFail(p)));
240
+ // A job file git couldn't read this time would let another job take its place: no job runs instead.
241
+ const failedRead = all.find((_, i) => tries[i] === FAILED);
242
+ if (failedRead)
243
+ return { jobs: [], problems: [], guarded: [], incomplete: `${failedRead} couldn't be read this time, so no job runs. The next push tries again.` };
244
+ const files = tries.map((f) => (f === FAILED ? null : f));
245
+ // A job file and a link to it, or two copies of one file, are one job. The real file wins over a link.
246
+ const kept = new Map();
247
+ const read = files.filter((f) => f !== null).sort((a, b) => Number(a.link) - Number(b.link) || a.path.localeCompare(b.path));
248
+ const readPaths = new Set(all.slice(0, MAX_JOB_FILES));
249
+ for (const f of read) {
250
+ // By the file it is, so a link and what it leads to are one, but two copies with the same text aren't.
251
+ const first = kept.get(f.target ?? f.path);
252
+ // A job could change the file a link leads to, unless it sits where no job may write.
253
+ if (f.target && !refusedPath(f.target))
254
+ problems.push({ source: f.path, problem: `is a link to ${f.target}, outside .mergelight: keep job files themselves in .mergelight` });
255
+ // A link to a file in .mergelight/jobs that isn't read as a job itself would run what is named as not read.
256
+ else if (f.target && /^\.mergelight\/jobs(?:\/|\.|$)/i.test(f.target) && !readPaths.has(f.target))
257
+ problems.push({ source: f.path, problem: `is a link to ${f.target}, which isn't a job file that is read` });
258
+ else if (first)
259
+ problems.push({ source: f.path, problem: `is the same file as ${first.path}, so its job counts once`, ...(f.target ? { target: f.target } : {}) });
260
+ else
261
+ kept.set(f.target ?? f.path, f);
262
+ }
263
+ // A skill that isn't on the base branch: the job would run without what the team meant it to follow.
264
+ // Only an ordinary SKILL.md counts, as the skill copy takes no links.
265
+ const parsed = readJobs([...kept.values()], (folder) => ["100644", "100755"].includes(tree.mode(`${folder}/SKILL.md`) ?? ""));
266
+ // A SKILL.md the skill copy won't take: empty, or over its size. Said now, not as a failed job each run.
267
+ for (const job of [...parsed.jobs]) {
268
+ if (!job.skill)
269
+ continue;
270
+ const size = await tree.size(`${job.skill}/SKILL.md`);
271
+ if (size !== null && (size === 0 || size > MAX_SKILL_FILE_BYTES)) {
272
+ parsed.jobs.splice(parsed.jobs.indexOf(job), 1);
273
+ parsed.problems.push({ source: job.source, problem: `its skill's SKILL.md is ${size === 0 ? "empty" : `over ${MAX_SKILL_FILE_BYTES / 1000} KB`}, so the skill can't be used` });
274
+ }
275
+ }
276
+ // No job to run: no guard to work out, and nothing to say about one.
277
+ // A link to a file that couldn't be a job doesn't "count once": say where the reason is.
278
+ const refusedSources = new Set(parsed.problems.map((p) => p.source));
279
+ for (const p of problems) {
280
+ const same = /is the same file as (.+?), so its job counts once/.exec(p.problem)?.[1];
281
+ if (same && refusedSources.has(same))
282
+ p.problem = `is a link to ${p.target ?? same}, which doesn't run as a job: see ${same}`;
283
+ }
284
+ // A skill named through a linked folder: the copy only takes the real folder, so say that, not "no SKILL.md".
285
+ for (const p of parsed.problems) {
286
+ const skill = /its skill (\S+) has no SKILL\.md/.exec(p.problem)?.[1];
287
+ const parts = skill?.split("/") ?? [];
288
+ const linked = parts.map((_, i) => parts.slice(0, i + 1).join("/")).find((at) => tree.mode(at) === "120000");
289
+ if (linked)
290
+ p.problem = `its skill ${skill} is reached through ${linked}, which is a link: name the skill by its real folder`;
291
+ else if (skill && tree.mode(`${skill}/SKILL.md`) === "120000")
292
+ p.problem = `its skill ${skill} has a SKILL.md that is a link: it must be a real file`;
293
+ }
294
+ const unread = all.slice(0, MAX_JOB_FILES).filter((_, i) => files[i] === null).map((source) => ({ source, problem: "couldn't be read: it is empty, too large, or a link to something that isn't a file in the repository" }));
295
+ const past = all.slice(MAX_JOB_FILES).map((source) => ({ source, problem: `only ${MAX_JOB_FILES} job files are read` }));
296
+ // A file no job may change can be a link to one it could, like AGENTS.md to docs/ai-guide.md. Every link
297
+ // from a protected file or folder is followed the way the file system would, through links in its
298
+ // folders too, and every file and folder on the way is guarded. Links inside what that guards are
299
+ // followed in turn, until nothing new turns up. If that can't be worked out in full, no job runs: the
300
+ // guard is never quietly smaller than it should be.
301
+ const sorted = [...parsed.problems, ...problems, ...unread, ...past].map(({ source, problem }) => ({ source, problem })).sort((a, b) => a.source.localeCompare(b.source));
302
+ // guardFor: the guard of this tree for those jobs, the base branch's, whatever jobs the tree itself has.
303
+ const guarding = guardFor ?? parsed.jobs;
304
+ if (!guarding.length)
305
+ return { jobs: [], problems: sorted, guarded: [] };
306
+ const targets = new Set();
307
+ const folders = guardedFolders(tree.paths, guarding);
308
+ // In any letter case, as a disk that ignores it opens Docs and docs as one folder: links and instruction
309
+ // files under either spelling are followed.
310
+ const inGuard = (p) => {
311
+ const f = folded(p);
312
+ return refusedPath(p) || [...folders, ...targets].some((t) => f === folded(t) || f.startsWith(`${folded(t)}/`));
313
+ };
314
+ /**
315
+ * A path with every link in it and in its folders followed, part by part, the way the file system does:
316
+ * a link is followed before a ".." after it is applied. Where it ends is guarded. Null when it leaves
317
+ * the repository; "deep" past the limit of links, or at the repository's root.
318
+ */
319
+ /** Every file, link and folder of the tree by its name in any letter case, built once. */
320
+ let byCase;
321
+ const caseFits = (path) => {
322
+ if (!byCase) {
323
+ const index = new Map();
324
+ for (const p of tree.paths) {
325
+ const parts = p.split("/");
326
+ for (let i = 1; i <= parts.length; i++) {
327
+ const at = parts.slice(0, i).join("/");
328
+ const key = folded(at);
329
+ index.set(key, (index.get(key) ?? new Set()).add(at));
330
+ }
331
+ }
332
+ byCase = new Map([...index].map(([k, v]) => [k, [...v]]));
333
+ }
334
+ return byCase.get(folded(path)) ?? [];
335
+ };
336
+ const resolve = async (path, guard = true) => {
337
+ const done = [];
338
+ let rest = path.split("/");
339
+ let hops = 0;
340
+ /** Folders that hold a link on the way. No job may take a link away, so they stay folders. */
341
+ const held = new Set();
342
+ while (rest.length) {
343
+ const part = rest.shift();
344
+ if (part === "" || part === ".")
345
+ continue;
346
+ if (part === "..") {
347
+ if (!done.length)
348
+ return null;
349
+ // The folder it steps back out of must stay a folder for the path to lead anywhere: a job that
350
+ // emptied it would make a protected file disappear. So it is guarded too, along with all in it,
351
+ // unless a link sits in it, as when a link's own target starts with "..".
352
+ const leaving = done.join("/");
353
+ if (guard && !held.has(leaving))
354
+ targets.add(leaving);
355
+ done.pop();
356
+ continue;
357
+ }
358
+ let at = [...done, part].join("/");
359
+ // A disk that ignores letter case opens docs/alias.md for Docs/alias.md: the guard follows it there
360
+ // too. When two names fit, it can't tell which one is opened, so it gives up rather than guess.
361
+ // A name spelled exactly so is that one. Otherwise two that fit can't be told apart: it gives up
362
+ // rather than guess. Files whose names differ only in letter case are guarded alike anyway, as
363
+ // the guard compares names in any letter case.
364
+ if (tree.mode(at) === undefined) {
365
+ const fits = caseFits(at);
366
+ if (fits.length && !fits.includes(at)) {
367
+ if (fits.length > 1)
368
+ return "deep";
369
+ at = fits[0];
370
+ // The folders on the way as the tree spells them, such as docs for Docs, so the file guarded
371
+ // and read for its imports is the real one.
372
+ done.splice(0, done.length, ...at.split("/").slice(0, -1));
373
+ }
374
+ }
375
+ const real = at.split("/").pop();
376
+ if (tree.mode(at) !== "120000") {
377
+ done.push(real);
378
+ continue;
379
+ }
380
+ if (++hops > MAX_LINK_HOPS)
381
+ return "deep";
382
+ for (let i = 1; i <= done.length; i++)
383
+ held.add(done.slice(0, i).join("/"));
384
+ const content = await tree.linkContent(at);
385
+ if (content === "unread")
386
+ return "unread";
387
+ // A link to an absolute path leads out of the repository. One to another link goes on from where it sits.
388
+ if (content === null || content.startsWith("/"))
389
+ return null;
390
+ rest = [...content.split("/"), ...rest];
391
+ }
392
+ // A link to the repository's root would guard every file: that can't be told apart from a mistake.
393
+ if (!done.length)
394
+ return "deep";
395
+ const end = done.join("/");
396
+ // Guarded even when its own name is refused: a folder named like a refused file isn't refused inside.
397
+ if (guard)
398
+ targets.add(end);
399
+ return end;
400
+ };
401
+ const followed = new Set();
402
+ let incomplete;
403
+ for (;;) {
404
+ const todo = tree.paths.filter((p) => tree.mode(p) === "120000" && !followed.has(p) && inGuard(p));
405
+ if (!todo.length)
406
+ break;
407
+ if (followed.size + todo.length > MAX_GUARDED_LINKS) {
408
+ incomplete = `The base branch has more than ${MAX_GUARDED_LINKS} links from files no job may change, so no job runs.`;
409
+ break;
410
+ }
411
+ for (const link of todo) {
412
+ followed.add(link);
413
+ // The review's own reader (read, above) joins a link's target as text, trimmed: guard that reading too.
414
+ const content = await tree.linkContent(link);
415
+ if (typeof content === "string" && content.trim() && !content.trim().startsWith("/")) {
416
+ const asRead = posix.normalize(posix.join(posix.dirname(link), content.trim())).replace(/\/+$/, "");
417
+ if (asRead && asRead !== "." && !asRead.startsWith(".."))
418
+ targets.add(asRead);
419
+ }
420
+ const end = await resolve(link);
421
+ if (end === "unread")
422
+ incomplete ??= `${link} couldn't be read this time, so no job runs. The next push tries again.`;
423
+ if (end === "deep")
424
+ incomplete ??= `${link} leads through more than ${MAX_LINK_HOPS} links, or to the repository's root, so no job runs.`;
425
+ }
426
+ if (incomplete)
427
+ break;
428
+ }
429
+ // Instruction files can pull other files in, like "@docs/ai-guide.md" in CLAUDE.md, which Claude Code
430
+ // and Gemini CLI read as instructions too, up to 5 levels deep. Those files are guarded as well, through
431
+ // any links on the way. A name that only looks like an import is guarded too: guarding too much is safe.
432
+ if (!incomplete) {
433
+ // Instruction files wherever a job may not write: refused names, and those inside guarded folders
434
+ // and link targets, such as the rules in a folder .cursor links to.
435
+ const isInstructions = (p) => /\.mdc?$/i.test(p) && inGuard(p);
436
+ /** A file to scan, and the folders its imports are read from: its own, and the link's when it was reached through one. */
437
+ const queue = [];
438
+ const queued = new Set();
439
+ // Once for each folder a file's imports are read from: one reached again through a link is read from
440
+ // that link's folder too.
441
+ const enqueue = (path, dirs, depth) => {
442
+ if (depth >= MAX_IMPORT_DEPTH || !tree.mode(path))
443
+ return;
444
+ const fresh = [...new Set([posix.dirname(path), ...dirs])].filter((dir) => !queued.has(`${path}\0${dir}`));
445
+ if (!fresh.length)
446
+ return;
447
+ for (const dir of fresh)
448
+ queued.add(`${path}\0${dir}`);
449
+ queue.push({ path, dirs: fresh, depth });
450
+ };
451
+ const follow = async (path) => {
452
+ const end = await resolve(path);
453
+ if (end === "unread")
454
+ incomplete ??= `${path} couldn't be read this time, so no job runs. The next push tries again.`;
455
+ if (end === "deep")
456
+ incomplete ??= `${path} leads through more than ${MAX_LINK_HOPS} links, or to the repository's root, so no job runs.`;
457
+ return typeof end === "string" ? end : null;
458
+ };
459
+ // Each instruction file, and where a linked one really leads: a tool that opens it by the link's
460
+ // path reads its imports from the link's folder.
461
+ for (const p of tree.paths.filter(isInstructions)) {
462
+ const at = tree.mode(p) === "120000" ? await follow(p) : p;
463
+ if (at)
464
+ enqueue(at, [posix.dirname(p)], 0);
465
+ }
466
+ // A folder that is a link, like .claude to config/claude or packages/web to apps/web: the instruction
467
+ // files in it are opened through the link too, so their imports are read from the folder they have
468
+ // there as well. Through a guarded link every Markdown file counts; through any other, only
469
+ // instruction files, and the folder itself isn't guarded for it.
470
+ const markdown = tree.paths.filter((p) => /\.mdc?$/i.test(p));
471
+ for (const link of tree.paths.filter((p) => tree.mode(p) === "120000")) {
472
+ const guardedLink = inGuard(link);
473
+ const end = guardedLink ? await follow(link) : await resolve(link, false);
474
+ // An ordinary link to the root, or one too deep, holds no instruction file of its own that isn't
475
+ // read already; only one git couldn't read this time leaves the guard unsure.
476
+ if (end === "unread") {
477
+ incomplete ??= `${link} couldn't be read this time, so no job runs. The next push tries again.`;
478
+ break;
479
+ }
480
+ if (typeof end !== "string" || end === "deep")
481
+ continue;
482
+ for (const p of markdown) {
483
+ if (!folded(p).startsWith(`${folded(end)}/`))
484
+ continue;
485
+ const through = `${link}/${p.slice(end.length + 1)}`;
486
+ if (guardedLink || isInstructions(p) || refusedPath(through))
487
+ enqueue(p, [posix.dirname(through)], 0);
488
+ }
489
+ }
490
+ const imported = new Set();
491
+ while (queue.length && !incomplete) {
492
+ const { path, dirs, depth } = queue.shift();
493
+ // A file that isn't Markdown, such as a package-lock.json named with @, is read up to a much higher
494
+ // limit: its imports count all the same, and it is often larger than any instruction file.
495
+ const limit = /\.mdc?$/i.test(path) ? MAX_INSTRUCTIONS_BYTES : MAX_IMPORTED_FILE_BYTES;
496
+ const file = await tree.readOrFail(path, limit);
497
+ if (file === FAILED) {
498
+ incomplete = `${path} couldn't be read this time, so no job runs. The next push tries again.`;
499
+ break;
500
+ }
501
+ // Too large to read for its imports: no job runs rather than one with a smaller guard.
502
+ if (file === null && ((await tree.size(path)) ?? 0) > limit) {
503
+ incomplete = `${path} is too large to check what it imports, so no job runs.`;
504
+ break;
505
+ }
506
+ for (const m of file?.text.matchAll(/(?:^|\s)@(\S+)/g) ?? []) {
507
+ // A full stop, comma or bracket after it ends the sentence, not the path. A home or absolute path is outside the repository.
508
+ const raw = m[1].replace(/[.,;:)\]]+$/, "");
509
+ if (!raw || raw.startsWith("~") || raw.startsWith("/"))
510
+ continue;
511
+ for (const dir of dirs) {
512
+ const joined = posix.normalize(posix.join(dir, raw)).replace(/\/+$/, "");
513
+ if (!joined || joined === "." || joined.startsWith("..") || imported.has(joined))
514
+ continue;
515
+ imported.add(joined);
516
+ // Guarding a name is cheap, so the limit is high: it only stops a run that would take too long.
517
+ if (imported.size > MAX_IMPORTS) {
518
+ incomplete = `The base branch's instruction files name more than ${MAX_IMPORTS} files, so no job runs.`;
519
+ break;
520
+ }
521
+ targets.add(joined);
522
+ const at = await follow(joined);
523
+ if (at)
524
+ enqueue(at, [posix.dirname(joined)], depth + 1);
525
+ }
526
+ if (incomplete)
527
+ break;
528
+ }
529
+ }
530
+ }
531
+ // Every link is guarded too, whatever folder it sits in: a job never writes at or through a link, so a
532
+ // link like docs/ci to .github/workflows can't carry a change into a protected place.
533
+ const links = tree.paths.filter((p) => tree.mode(p) === "120000");
534
+ const guarded = [...new Set([...folders, ...targets, ...links])].sort();
535
+ // A guard that couldn't be worked out in full hands out no job, whatever reads them.
536
+ return incomplete ? { jobs: [], problems: sorted, guarded, incomplete } : { jobs: parsed.jobs, problems: sorted, guarded };
537
+ }
538
+ /**
539
+ * What the head guards: the files its own links and instruction files lead to, worked out the way the
540
+ * base branch's are. A pull request can only add to the guard this way, never take from it, and the
541
+ * jobs on the head never count. A head that can't be worked out in full says why.
542
+ */
543
+ export async function headGuarded(mirror, head, jobs) {
544
+ const { guarded, incomplete } = await jobFilesFor(mirror, head, jobs);
545
+ if (incomplete)
546
+ return { why: `The pull request's own links and instruction files couldn't be checked in full: ${incomplete.replace(/^The base branch/, "The pull request")}` };
547
+ return { guarded };
548
+ }
549
+ /** The largest SKILL.md the skill copy takes (skills.ts). */
550
+ const MAX_SKILL_FILE_BYTES = 60_000;
551
+ /** How many links from files no job may change are followed, to guard what they lead to, and how far each. */
552
+ const MAX_GUARDED_LINKS = 1000;
553
+ const MAX_LINK_HOPS = 10;
554
+ /** How deep instruction files' @ imports are followed, as Claude Code does, how many names are guarded at most, and how large a file is read for them. */
555
+ const MAX_IMPORT_DEPTH = 5;
556
+ const MAX_IMPORTS = 20_000;
557
+ const MAX_INSTRUCTIONS_BYTES = 4_000_000;
558
+ /** How large any other file named with @ may be and still be read for its imports. */
559
+ const MAX_IMPORTED_FILE_BYTES = 64_000_000;
560
+ /** How many rule files are read at most. */
561
+ const MAX_RULE_FILES = 100;
562
+ /**
563
+ * The team's instruction files and rule files, as the base branch has them, from one listing of it.
564
+ * Conventions are background for the reviewers; rules are what they check (repo-rules.ts).
565
+ */
566
+ export async function teamFilesFor(mirror, base, changedPaths = []) {
567
+ const none = { conventions: [], rules: [], unreadRules: [], droppedRules: 0 };
568
+ const tree = await baseTree(mirror, base);
569
+ if (!tree)
570
+ return none;
571
+ const { read } = tree;
572
+ const allRulePaths = tree.paths.filter((p) => RULE_FILE.test(p)).sort((a, b) => Number(!a.startsWith(".mergelight/")) - Number(!b.startsWith(".mergelight/")) || a.localeCompare(b));
573
+ const rulePaths = allRulePaths.slice(0, MAX_RULE_FILES);
574
+ // Both kinds at once: one slow read mustn't leave the other no time.
575
+ const [found, ruleFiles] = await Promise.all([
576
+ Promise.all(conventionPaths(tree.paths, changedPaths).slice(0, MAX_CONVENTION_FILES * 2).map(read)),
577
+ Promise.all(rulePaths.map(read)),
578
+ ]);
170
579
  const conventions = [];
171
580
  const seen = new Set();
172
581
  let total = 0;
@@ -181,7 +590,16 @@ export async function conventionsFor(mirror, base, changedPaths = []) {
181
590
  conventions.push({ path: f.path, text: f.text.slice(0, room), truncated: f.text.length > room });
182
591
  total += Math.min(f.text.length, room);
183
592
  }
184
- return conventions;
593
+ // A rule file and a link to it are one file: its rules count once.
594
+ const seenRules = new Set();
595
+ const readRules = ruleFiles.filter((f) => f !== null && !seenRules.has(f.sha) && Boolean(seenRules.add(f.sha)));
596
+ const stats = { dropped: 0 };
597
+ const rules = repoRules(readRules, changedPaths.length ? changedPaths : undefined, stats);
598
+ // A rule file that couldn't be read is named, never dropped without a word.
599
+ // Read but with no rules in it (a Copilot file without applyTo, say), or past the limit of files: named too.
600
+ const noRules = readRules.filter((f) => parseRuleFile(f.path, f.text).length === 0).map((f) => f.path);
601
+ const unreadRules = [...rulePaths.filter((_, i) => ruleFiles[i] === null), ...noRules, ...allRulePaths.slice(MAX_RULE_FILES)];
602
+ return { conventions, rules, unreadRules, droppedRules: stats.dropped };
185
603
  }
186
604
  /** The answer, or the fallback once the time is up, for work that must never hold up a review. */
187
605
  async function withDeadline(work, ms, fallback) {
@@ -230,6 +648,46 @@ async function withLock(dir, fn) {
230
648
  rmSync(lock, { recursive: true, force: true });
231
649
  }
232
650
  }
651
+ /**
652
+ * The mirror with the pull request's head and its base branch fetched, for the push step, which reads the
653
+ * team's files and the head's file modes but checks nothing out. The team's files come from the base
654
+ * branch as it is now. When it can't be fetched, this throws: an older commit could hold jobs the team
655
+ * has since taken out, so the push never falls back to one.
656
+ */
657
+ export async function fetchMirror(pr) {
658
+ const mirror = join(cacheDir(), "repos", pr.owner, `${pr.repo}.git`);
659
+ mkdirSync(join(cacheDir(), "repos", pr.owner), { recursive: true });
660
+ if (!existsSync(mirror)) {
661
+ // Cloned beside it and moved into place in one step: the lock lives in the mirror, so two runs on a
662
+ // shared cache can't both be cloning into the same folder. The one that comes second keeps the first's.
663
+ const fresh = mkdtempSync(`${mirror}.new-`);
664
+ try {
665
+ await git(["clone", "--bare", "--filter=blob:none", "--quiet", `https://github.com/${pr.owner}/${pr.repo}.git`, fresh]);
666
+ try {
667
+ renameSync(fresh, mirror);
668
+ }
669
+ catch {
670
+ // Another run put its clone there first.
671
+ }
672
+ }
673
+ finally {
674
+ rmSync(fresh, { recursive: true, force: true });
675
+ }
676
+ }
677
+ return withLock(mirror, async () => {
678
+ const fetch = (...refspecs) => git(["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "origin", ...refspecs], mirror);
679
+ await fetch(`+refs/pull/${pr.number}/head:refs/mergelight/pull/${pr.number}`);
680
+ if (!(await hasCommit(mirror, pr.headSha)))
681
+ await fetch(pr.headSha);
682
+ // Into a ref of this pull request's own: a cached ref of an older branch, such as base/release when
683
+ // the base is now release/2, can't block it.
684
+ const ref = `refs/mergelight/push/${pr.number}/base`;
685
+ await fetch(`+refs/heads/${pr.baseRef}:${ref}`);
686
+ // Pinned to one commit under the lock, as the jobs step does, so a later fetch can't move it.
687
+ const pinned = (await git(["rev-parse", "--verify", `${ref}^{commit}`], mirror)).stdout.trim();
688
+ return { mirror, teamBase: pinned };
689
+ });
690
+ }
233
691
  /**
234
692
  * Keeps a blobless bare mirror of the repository in the cache, fetches the PR,
235
693
  * and checks out the commit under review in a temporary worktree.
@@ -294,7 +752,8 @@ export async function prepareWorkspace(pr, at, skillFolders = [], writtenSkills
294
752
  // the commit it branched from either. Its author picks that commit, and could pick one from
295
753
  // before a skill was written or tightened.
296
754
  // The same goes for the instruction files.
297
- const teamBase = haveBaseBranch ? `refs/mergelight/base/${pr.baseRef}` : baseCandidate;
755
+ // As one commit, read while the mirror is locked: another run can move the branch's ref later.
756
+ const teamBase = (await git(["rev-parse", "--verify", `${haveBaseBranch ? `refs/mergelight/base/${pr.baseRef}` : baseCandidate}^{commit}`], mirror)).stdout.trim();
298
757
  const skills = await skillsFor(mirror, teamBase, dir, skillFolders);
299
758
  // The skills the team wrote on its dashboard go next to them. A skill that can't be written is one fewer, never a failed review.
300
759
  let written = [];
@@ -304,9 +763,11 @@ export async function prepareWorkspace(pr, at, skillFolders = [], writtenSkills
304
763
  catch {
305
764
  written = [];
306
765
  }
307
- const conventions = await withDeadline(conventionsFor(mirror, teamBase, touchedPaths), SKILL_IMPORT_TIMEOUT_MS + 2 * SKILL_GIT_TIMEOUT_MS, []);
766
+ const { conventions, rules: repoRuleList, unreadRules, droppedRules, timedOut } = await withDeadline(teamFilesFor(mirror, teamBase, touchedPaths), SKILL_IMPORT_TIMEOUT_MS + 2 * SKILL_GIT_TIMEOUT_MS, { conventions: [], rules: [], unreadRules: [], droppedRules: 0, timedOut: true });
308
767
  return {
309
768
  dir,
769
+ mirror,
770
+ teamBase,
310
771
  mergeBase,
311
772
  headSha,
312
773
  diff,
@@ -317,6 +778,10 @@ export async function prepareWorkspace(pr, at, skillFolders = [], writtenSkills
317
778
  skills,
318
779
  writtenSkills: written,
319
780
  conventions,
781
+ rules: repoRuleList,
782
+ unreadRules,
783
+ droppedRules,
784
+ teamFilesLate: timedOut === true,
320
785
  cleanup: async () => {
321
786
  await run("git", ["-C", mirror, "worktree", "remove", "--force", dir]);
322
787
  rmSync(dir, { recursive: true, force: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mergelight/cli",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "description": "AI code review that runs on the Claude or ChatGPT plan you already pay for.",
5
5
  "type": "module",
6
6
  "bin": {